Antd modal not opening / closing when using MobX state

Viewed 116

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;
}
 }
2 Answers

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 >

Mmmh sounds strange. Can you add this code and tell me if it works ?

  const [openContactForm,setOpenContactForm] = useState(false)

  useEffect(()=>{
    if(openContactForm !== store.contactFormOpen) {
      setOpenContactForm(store.contactForm)
    }
  },[store.contactFormOpen])

And change your JSX to this:

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