Unable to load data in page load using MobX and React js

Viewed 303

I am new MobX with react.js and I am very excited to explore more about react. I googled a lot and tried the sample with the help of the below link, but no luck.

Enabling decorators - MobX

Can someone please step in and help me with this? I am doing this as a POC to start my project. It is a blocker and it means a lot for me at this time

model.ts

export interface IActivity {
    id: string;
    title: string;
    description: string;
    category: string;
    date: string;
    city: string;
    venue: string;
}

agent.ts

import axios, { AxiosResponse } from 'axios';

axios.defaults.baseURL = 'https://localhost:xxx/api';

const responseBody = (response: AxiosResponse) => response.data;
const requests = { get: (url: string) => axios.get(url).then(responseBody) };
const Activities = { list: () => requests.get('/activities/getactivities') };

// eslint-disable-next-line import/no-anonymous-default-export
export default { Activities };

activityStore.ts

import { observable, action, makeObservable } from 'mobx';
import { createContext } from 'react';
import { IActivity } from './../models/agent';
import agent from '../api/agent';

class ActivityStore {
    @observable activities: IActivity[] = [];

    constructor() {
        makeObservable(this);
    }

    @action loadActivities = () => {
        agent.Activities.list().then((response) => {
            this.activities.push(response);
        });
    };
}

export const activityStoreContext = createContext(new ActivityStore());

App.tsx

import { useContext, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { activityStoreContext } from '../src/stores/activityStore';

const App = observer(() => {
    const activityStore = useContext(activityStoreContext);

    const display = activityStore.activities.map((activity) => (
        <li key={activity.id}>{activity.title}</li>
    ));

    useEffect(() => {
        activityStore.loadActivities();
    }, [activityStore]);

    return (
        <div>
            <ul>{display}</ul>
        </div>
    );
});

export default App;

package.json

enter image description here

Output from edge browser (same in chrome and firefox as well) enter image description here

1 Answers

Decorators alone are not enough in mobx@6.0.0 or later versions. You need to use makeObservable(this) in the constructor of ActivityStore as well.

If the response to agent.Activities.list() is an array, you likely want to push all the elements in this array to the this.activities array, not push the entire array.

agent.Activities.list().then((response) => {
    this.activities.push(...response);
});
Related