Fetch Requests in React
When I first started learning React one of my biggest hurdles was understand exactly what a fetch call is. I was also sadly disappointed as I scoured the internet I noticed there wasn’t any straight forward documentation solely breaking down the basics of a fetch requests to an API. So let this be you’re quick tip guide on how to write a fetch request!
First and foremost when writing fetch requests in React you can write a fetch request within any function but it generally frowned upon. It would benefit you to use common practice and place all your fetch requests within a custom function offered to you by react. Known as the componentDidMount function.
This magical function will not only organize your code but also make this fetch request when the page loads so you always have access to this data! Rather than having to trigger this function every time you want this information.
So let us break this down a bit further. Once you have your rails server started up with rails s, you should then have access to your API database through your controllers and routes.
//Written inside users_controller.rb
//Written inside config/routes.rb
In this example we will be looking at a users model. With localhost:3000/users you can now see how your data is structured.
Personally I find it more legible to save the API’s url to a variable but that’s really personal preference. Once you have the url you will want to place it within the fetch call telling javascript from which url to pull data from.
You will then (haha get it?) take that response and return it in json() format for you browser to be able to render the data that was retrieved.
Then (incase you didn’t get the joke the first time ) you will have access to your users in an Array with which you can do as you please. In this example I’m only console.logging the users array but you could also set State(third picture) and make POST DELETE UPDATE requests by adding objects!(fourth picture)
To think all this came from a simple fetch request.