Ben
Ben

Reputation: 16699

MobX - Reaction inside class component

Today I started using MobX and the first problem I ran into is how to execute a function in a React class component whenever an Observable updates.

I am under the impression this can be achieved using a reaction, but I'm not sure how to make it work.

class MissionLog {

    private _missions: Array<IMissionItem> = [];
    public get missions() {
        return this._missions;
    }

    constructor() {
        makeAutoObservable(this);
    }

    // Example of a method that modifies the _missions array
    public receiveMission(mission: IMissionItem) {
        this._missions.push(mission);
    }
}

export const missionLog = new MissionLog();

// Example of modifying the missions array
missionLog.receiveMission(someMission);

export const ObserverTest = observer(class _ObserverTest extends React.Component {
   
    constructor(props: any) {
        super(props);

        // Executes the console.log at the start,
        // but not when missionLog.missions changes.
        autorun(() => {
            console.log("Autorun", missionLog.missions);
        })

        // Never executes the console.log
        reaction(
            () => missionLog.missions,
            (mission) => {
                console.log("Reaction");
            }
        )
    }

    render() {
        return (
            // Accessing missionLog.missions here
            // gives me the correct, updated data,
            // so my setup should be fine.
        )
    }
});

I also tried to use intercept and observe instead of reaction, but also no result.

Upvotes: 0

Views: 1027

Answers (1)

Z. Bird
Z. Bird

Reputation: 50

Looks like we both ran into the same problem and thats poor documentation from Mobx :-D.

Correct me if I am wrong,but according to their documentation react() acts like an useEffect function in React.

You should basically place it anywhere where you need reaction in your app.

reaction(() => data, (data, reaction) => { sideEffect }, options?)

the first argument is accepting the data, that should be changing.

() => data

the second argument is fucntion where you say what happens, if the data changes.

(data, reaction) => { sideEffect }

Upvotes: 0

Related Questions