React Ant Design Modal Method update on state change

Viewed 6308

I'm currently migrating to antd, and have a modal appear on a certain route (ie /userid/info). I'm able to achieve this if I use the antd Modal react component, but I'd like to be able to use the modal methods provided such as Modal.confirm,Modal.info and Modal.error as they offer nicer ui straight out of the box.

I'm running to multiple issues such as having the modal rendered multiple times (both initially and after pressing delete in the delete user case), and unable to make it change due to state (ie display loading bar until data arrives). This is what i've tried but it constantly renders new modals, ive tried something else but that never changed out of displaying <Loader /> even though isFetching was false. I'm not sure what else to try.

const UserInfoFC: React.FC<Props> = (props) => {

  const user = props.user.id;

  const [isFetching, setIsFetching] = React.useState<boolean>(true);
  const [userInfo, setUserInfo] = React.useState<string>('');

  const modal = Modal.info({
    content: <Loader />,
    title: 'User Info',
  });

  const displayModal = () => {

    const renderInfo = (
      <React.Fragment>
        <p>display user.info</p>
      </React.Fragment>
    );

    const fetchInfo = async () => {
      try {
        user = // some api calls
        setUserInfo(user.info);
        modal.update({ content: renderInfo })
      } catch (error) {
        // todo
      }
      setIsFetching(false);
    };
    fetchInfo();
  };

  displayModal();

  return(<div />);
};

reference: https://ant.design/components/modal/#components-modal-demo-confirm

edit: here is a replication of one of the issues I face: https://codesandbox.io/embed/antd-reproduction-template-1jsy8

2 Answers

As mentioned in my comment, you can use a useEffect hook with an empty dependency array to run a function once when the component mounts. You can initiate an async call, wait for it to resolve and store the data in your state, and launch a modal with a second hook once the data arrives.

I made a sandbox here

Instead of going to /:id/info and routing to a component which would have returned an empty div but displayed a modal, I created a displayInfo component that displays a button and that controls the modal. I got rid of attempting to use routes for this.

What I have now is similar to the docs

Related