frsnmk
frsnmk

Reputation: 137

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

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?

Upvotes: 0

Views: 4029

Answers (4)

Nabeel
Nabeel

Reputation: 1

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");
            }
        })
     },[]);

Upvotes: 0

Sidharrth Nagappan
Sidharrth Nagappan

Reputation: 76

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

Upvotes: 1

smith chokshi
smith chokshi

Reputation: 236

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.

Upvotes: 1

Vivek Bharda
Vivek Bharda

Reputation: 1

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).

Upvotes: 0

Related Questions