How to Fetch API data with Axios and display it in a React app with hooks

How to Fetch API data with Axios and display it in a React app with hooks

Braincuber Technologies's photo
Braincuber Technologies
·Mar 24, 2022·

5 min read

Subscribe to my newsletter and never miss my upcoming articles

This article will go over how to fetch API data with Axios and display in React hooks, 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.

Basic Axios is the axios object, the HTTP method used, and the URL as a parameter. I saved the URL body as a variable, and added the endpoint notes inside the request (an optional step, but creates more readable code). Our request will be stored in a function called getAllNotes(). With the request, the parent component code looks like this:

How to Fetch API data with Axios.png

Axios is a promise-based library, so the promise must be handled. I am going to use then to handle the promise if it is fulfilled, and catch if it is rejected (aka, I get an error). Then is a callback function that automatically has the response object as an argument. That’s great for us, because the data we’re retrieving will be inside that response object. This is where things will be different based on the data that you’re retrieving. My entire GET request looks like this:

fetch data from api in javascript using axios.png

I save my data into a variable I call allNotes. I got response and data from the response object, and then drilled into my own data object to get notes, and finally allNotes. For reference, my data object looks like this:

braincuber-technologies-react-fetch-dat-from-api.png

The notes key contains the value allNotes, which is an array of 11 notes that each have an author, title, and content property. (MongoDB adds the _id and __v properties). We’re going to display this content on the frontend with React later. But first!

Make the GET request when the page renders

Our overview page should display all of our notes as soon as it loads. But right now the GET request is wrapped in a function. We will use the useEffect hook to call this function when the Parent component mounts. (I’m using React Router to show this component).

Add useEffect to your React import, and simply call the function inside the useEffect hook:

useEffect(() => {
     getAllNotes();
}, []);

useEffect runs after the component is rendered. Adding the empty brackets [ ] as an argument is necessary so the code doesn’t run in an infinite loop. This second argument tells useEffect to only render if certain values have changed. We’re essentially telling useEffect to only run on render, because we’re passing it an empty value. (Guess who is calling this out because she initially forgot to add it and made hundreds of API calls 🙃). Add the retrieved data to state and pass it to a child component.

We’re really in it now. Add useState to your import and let’s initialize our state. It is quite simple:

const [notes, getNotes] = useState('');

Now all we have to do is add the data we’ve retrieved from our GET request to the notes in our state. This is also very quick:

braincuber-react-tutorial.png

In just two lines of our code, our data is safely in our state object, and ready to be passed to a child component, where it will be displayed. Because we are good, law-abiding citizens, we are of course separating the logic components from the UI components. My child component is called , and I will pass it the state as a prop.

This is all the code of our parent component:

fetch-data-from-api-in-react-using-axios-hooks.png

Nice. Now we’re ready to display that data.

Loop through the data in the child component and display it.

The final step. I want each of my notes to be displayed in a notecard component that I’ve already made, so I passed my API data as props. I’m going to console.log my data to make sure it’s passed.

export default function NoteTimeline(props) {
console.log(props.note)
return(
     <>
     </>
)
}

In the console, I see my note objects!

react-js-api-fetch-data-output.png

I can go right ahead and do props.allNotes.map() and start dynamically filling my notes, right?

Almost. The API call from Express and updating state in the parent component is an asynchronous operation. If I try to map the props on render, I will get an error because my props will be undefined on load.

Instead of immediately mapping the note array, I check that notes.length > 0, so I know that the data has been updated in state before I map it. Here is the initial code from my child component, called NoteTimeline:

braincuber-react-with-axios.png

This is the entire code for the child component, where I also call the function displayNotes().

how-to-use-axios-with-react-hooks.png

Our notes look like this on the frontend:

output-react-hooks-axios.png

And that’s all. This article is the entire process to retrieve and display API data in a React app. I wrote it because I couldn’t find a good guide for this one operation online.

Visit braincuber.com for more opportunity

Did you find this article valuable?

Support Braincuber Technologies by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this