Categories
JavaScript Answers

How to use async/await inside a React functional component with JavaScript?

Spread the love

Sometimes, we want to use async/await inside a React functional component with JavaScript.

In this article, we’ll look at how to use async/await inside a React functional component with JavaScript.

How to use async/await inside a React functional component with JavaScript?

To use async/await inside a React functional component with JavaScript, we can define an async function inside the component.

For instance, we write

function Dashboard() {
  const [token, setToken] = useState("");

  const getToken = async () => {
    const headers = {
      Authorization: authProps.idToken,
    };
    const response = await axios.post(
      "https://foo.bar/get-token",
      {
        //...
      },
      { headers }
    );
    const data = await response.json();
    setToken(data.access_token);
  };

  useEffect(() => {
    if (!token) {
      getToken();
    }
  }, []);

  return <>...</>;
}

to define the getToken async function in the Dashboard component.

In it, we call axios.post to make a post request.

It returns a promise and we get the resolve value of the promise with await.

Then we call getToken in the useEffect callback if token is falsy.

Conclusion

To use async/await inside a React functional component with JavaScript, we can define an async function inside the component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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