Reputation: 519
I am building a React JS app with react-router v5. I have already set up a 404 page and it works well. As you can see, in the console I’m getting response code I just need to understand how to set a 404 header in the React component from this api response. I looked up this question and everyone says you should set it from server response, but I did not figure it out, because I'm here now for your help. Thank you
import React from "react";
const baseURL = "https://dog.ceo/api/breeds/image/";
const phpRoute = "giveme404"; //if you put here "random" will work
class NotFoundPage extends React.Component {
componentDidMount() {
fetch(baseURL + phpRoute)
.then(response => response.json())
.then(function(response) {
console.log(response);
});
}
render() {
return <div>404 Error, Page not found</div>;
}
}
export default NotFoundPage;
Get response from server to React
Upvotes: 0
Views: 1119
Reputation: 1259
Here's an example error handling strategy you can adopt on the frontend.
Some highlights:
fetch
method in JS offers the same control as axios
in terms of global
error handling. Logic for api access logic is in api.js file, there
you can see I added an error interceptor (more about interceptors here) which kicks off whenever
there's an unhandled http error and redirects to the not found page
only in case of 404 status code.componentDidMount
I
store that value in a global variable so I have access to it in the
api logic, but you'll need to come up with better approach I think, it's just for demo purposes.Outside of this sample, error boundaries are nifty mechanism to handle errors in your render functions (not event handlers) (for either class or functional components). In my experience, I've used them mostly with the render-as-you-fetch strategy to incorporate them with the error boundaries. With that approach the request is effectively made in the render function as opposed to any callbacks like componentDidMount
. But this is probably not the standard yet and official support will come probably in next major version, React 17.
I hope that helps, let me know if you have questions. ;)
Upvotes: 1