This article will go over how to fetch data with Axios in React, save it to state, and then display it in a React component.

I route my data using an Express backend and store it in MongoDB, but this article won’t be about that. It assumes that you have a known endpoint and a datasource. The method described can be done with any API, but I am using an endpoint I created in Express, so my url will be my local host.

We will use two components here: a parent component to get the data, and then a child component to display the data. This page is going to be an overview page for notes that I have stored in my database. The notes will dynamically render in my React app with their own card that contains their title and content.

Import axios and make a GET request

Use npm i axios to install axios and then add it as an import to your parent component. I’m going to use axios to get all of my notes, which I stored in a database.

Now that axios is installed, we can use it to make a GET request to retrieve all of the notes in our database. We want to store this request inside a function.

#react #mongodb #api #hooks

Fetch API data with Axios and display it in a React app with hooks
3.05 GEEK