Home > Enterprise >  How to redirect route with id to not found if id doesn't exist in react router
How to redirect route with id to not found if id doesn't exist in react router

Time:04-11

I have a route with id patients/:id. I'm typing route in a browser like this patients/10 and it shows data of a patient with id 10. The problem is when I'm typing an id that does not exist in DB it returns blank data. My expectation is, that it returns to page 404 or something like that. Is there a way for me to do that?

CodePudding user response:

Yes, this is possible. I'm assuming that your React frontend is querying the server for each patient.

Upon making the request on the page, you could check to see if the response body is empty. If it is empty, you could redirect to a 404. If there is data, you can continue to print data on the page.

const isEmpty = Object.keys(obj).length === 0;
if isEmpty(response) {
    return <Redirect to="/your-404-route" />
}
// continue to print details below

CodePudding user response:

Yes you can achieve this thing by placing a condition in your API call, i.e, if your API throws an error of 404 then you simply redirect to 404-page using this.props.history.push('/404'), this is an example you can use this as a reference.

CodePudding user response:

For this first, you check the data that exits in the database or not. If the data is exiting in the DB then it redirects as patients/10 URL otherwise its redirects to /error-page (error page route name).

CodePudding user response:

Simply use the Navigate or useNavigate hook from react-router-dom

import { useNavigate } from "react-router-dom"; let navigate = useNavigate();

    useEffect(() => {
       apiCall().then((response) => {
         setData(response.data)
      }).catch((error)=>{
          const {response} = error.response.data
            if (response.statusText === 404){
              navigate("/errorpage");
            }
        })
     },[]);
  • Related