reactjsmobxmobx-react

Can't replace state with object in mobx store


I'm trying to replace mobx store prop with an object. The problem is that I want it to be at first non-initialized – but when I update prop (it called agreement in code) it seems mobx just don't see that prop and components aren't updating.

    class ExportContractStore {
        agreement: AgreementT;
    
        constructor() {
            makeAutoObservable(this);
        }
    
        setCurrentAgreement(agreement: AgreementT) {
            this.agreement = agreement;
        }
    }

If I initialize agreement with empty object then I get error on prop update:

Uncaught (in promise) RangeError: Maximum call stack size exceeded

In React components, I'd like to use it this way:

export const AgreementList = observer(({ agreements }: PropsT) => {
    const agreementsList = agreements.map((agreement) => {
        const { id } = agreement.record;
        const onClick = () => {
            exportContractStore.setCurrentAgreement(agreement);
        };

        return <button>{`№ ${id}`}</button>
    });

    return <ul className='docs'>{agreementsList}</ul>;
});

export const ExportContractSection = observer(() => {
    const { initObj } = useInitContractSection();
    useEffect(() => {
        console.log(exportContractStore.agreement);
    });

    return (
        <div className='section'>
            <div className='choose-agreement'>
                <h2>Choose contract</h2>
                <AgreementList agreements={initObj.agreements} />
            </div>
            //agreement here not just boolean - I need this object many times in 
            //different components as well
            {exportContractStore.agreement ? (
                <Form className='form'>
                   ...
                </Form>
            ) : null}
        </div>
    );
});

So, the issue is if it's possible in mobx store to replace a whole property object with another object?


Solution

  • So the problem was in the object “agreement” that contains props which recursively links object itself – since that, I was getting error from mobx about call stack exceed.

    Instead of putting a whole object, I decided to store just a key (agreement number) and by this key getting an object from array. It's not really comfortable, but the only way that I found possible to resolve an issue.