Home > other >  how to Open a modal inside of a response async?
how to Open a modal inside of a response async?

Time:05-21

hi i'm trying to open a modal when my api response with a error but it don't render my modal or do you have other idea how show a modal everytime the api give a error ?

const useEmbedContent = (resourceId) => {
  const [resourceBase64File, setResourceBase64File] = React.useState(null);
  const [resourceFile, setResourceFile] = React.useState(null);
  const [error, setError] = React.useState('');

  const [isOpen, setIsOpen] = React.useState(false);

  const loadResourceFile = async () => {
    try {
      const file = await resourceDetailBlobApi.create({_id: resourceId});

      setResourceFile(file);
   
      const base64 = await fileToBase64(file);

      setResourceBase64File(base64);
    } catch (createError) {

      // modal status
      setIsOpen(true)

   {isOpen && <Modal setIsOpen={setIsOpen} />}

      setResourceFile(null);
      setResourceBase64File(null);
      setError(createError);
    }
  };

  React.useEffect(() => {
    loadResourceFile();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
   
  return {

    resourceBase64File,
    resourceArrayBuffer: resourceFile,
    error
  };
};

CodePudding user response:

Move {isOpen && <Modal setIsOpen={setIsOpen} />} to your component or page you want to show modal:

In yourpage.js or yourcomponent.js:

export default funtion YourComponent({setIsOpen}){
  return(
   <>
    {isOpen && <Modal setIsOpen={setIsOpen} />} //<== Move to inside your Component or your Page
   </>  
 )
}

CodePudding user response:

It seems are you trying to create custom hook. Anyway, you are already returning the error state. So based on the error state, you can render the model

const ModalComponent = () => {
  const { error } = useEmbedContent()

  return (
      <>
      { error && <Modal setIsOpen={setIsOpen} />}
      </>
  )
}
  • Related