Home > Mobile >  How to use React to show a dialog when api detect HTTP Status is 401
How to use React to show a dialog when api detect HTTP Status is 401

Time:09-16

I am new to web development.I want to use React to show a dialog when the HTTP status is 401.How to trigger App page to show dialog when the status is 401

CodePudding user response:

Here is an example on how to make an HTTP request and how to access/check the HTTP response status code:

async function makeRequest() {
    try {
        const response = await fetch('https://randomlink.com/api/');

        if (response.status === 401) {
            // open modal
        }
    } catch (err) {
        console.log(err);
    }
}

await makeRequest();

CodePudding user response:

First of all, you should use useState to contain the dialog status (default value is false). The value is used by DialogComponent (Example: From any library as MUi, Antd,...) In the API function, you can use try/catch in order to catch the error status. Then you use setState to update the dialog's state.

Example:

    const [isOpen, setIsOpen] = useState(false)
    
    const getData = async() => {
       try {
         await getDataFromApi()
       } catch (error) {
        if (axios.isAxiosError(error) && error.response.status === 401) {
          // do something ...
          setIsOpen(true)
        }
       }
    }

    return (
      <div>
       // components...
       <DialogComponent isOpen={isOpen}/>
      </div>
   )
  • Related