Search code examples
javascriptreactjsantdmobx

Antd modal not opening / closing when using MobX state


I have a simple MobX store that has a bool var contactFormOpen and function to set setContactFormOpen. It is working when clicking outside the modal or on cancel I can see that it changes but the modal doesn't open or close.

const handleCancel = (e: any) => {
e.stopPropagation();
store.setContactFormOpen(false);
};

return (
    <Modal title="Contact us" visible={store.contactFormOpen} width={740} centered footer={null} onCancel={(e) => handleCancel(e)}>
        <h1>Contact form</h1>
    </Modal>
)

In the console log I can see that store.contactFormOpen is changing from true to false, but the modal is not closing or opening. Any ideas? Thanks!

The store :

export default class store {
contactFormOpen = false;

constructor() {
    makeAutoObservable(this)
}

setContactFormOpen = (isOpen: boolean) => {
    this.contactFormOpen = isOpen;
}
 }

Solution

  • It's hard to understand what your application looks like from your description, but it's clear that you missed at least one important thing: for a component to know about changes to the store, it must be wrapped in an observer.

    I reproduced approximately your application and here is a link where you can see how it should be implemented:

    Codesandbox link >