Sometimes, we want to use async
and await
inside a React functional component.
In this article, we’ll look at how to use async
and await
inside a React functional component.
How to use async and await inside a React functional component?
To use async
and await
inside a React functional component, we can define an async function inside the component and call it.
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 defined the getAnswer
async function that calls axios
to make a GET request to the API endpoint we want.
Then we get the data
property from the object returned with the promise to get the response data.
Next, we call getAnswer
in the useEffect
callback to call it when we mount the component.
Conclusion
To use async
and await
inside a React functional component, we can define an async function inside the component and call it.