Categories
React Answers

How to Use Async and Await with Axios in React?

Spread the love

Sometimes, we want to use async and await with Axios in React.

In this article, we’ll look at how to use async and await with Axios in React.

Use Async and Await with Axios in React

To use async and await with Axios in React, we can call axios in an async function.

For instance, we write:

import axios from "axios";
import React, { useEffect, useState } from "react";

export default function App() {
  const [val, setVal] = useState();

  const getAnswer = async () => {
    const { data } = await axios("https://yesno.wtf/api");
    setVal(data.answer);
  };

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

  return <div>{val}</div>;
}

We call axios with the URL we want to make a GET request to.

It returns a promise that resolves to an object with the data property set to the response data.

So we use await to return the resolved value from the promise.

Then we call setVal with the data.answer property to set the value of val and display that in a div.

Conclusion

To use async and await with Axios in React, we can call axios in an async function.

Leave a Reply

Your email address will not be published. Required fields are marked *