Notes

Axios with async await in React

Edit on GitHub

ReactJS

Normally, you can do an async/await axios request like so:

1// Want to use async/await? Add the `async` keyword to your outer function/method.
2async function getUser() {
3  try {
4    const response = await axios.get('/user?ID=12345');
5    console.log(response);
6  } catch (error) {
7    console.error(error);
8  }
9}

In React, Promises or asnyc functions are not supported inside useEffect, you can only return a cleanup function. There will be a related error in the Console. The recommened approach is to define your async function inside the Effect and then call it immediately

So, this:

1useEffect(() => {
2  const fetchData = async () => {
3    const result = await axios(
4      'https://hn.algolia.com/api/v1/search?query=redux',
5    );
6    setData(result.data);
7  };
8  fetchData();
9}, []);

instead of this:

1useEffect(async () => {
2  const result = await axios(
3    'https://hn.algolia.com/api/v1/search?query=redux',
4  );
5  setData(result.data);
6})

In the following examples, the promise resolving happens with async/await.

GET

1let getUsers = async () => {
2    let response = await axios.get("https://reqres.in/api/users?page=1");
3    let { data } = response.data;
4    this.setState({ users: data });
5}

POST

1let getUsers = async () => {
2    let response = await axios.post("https://reqres.in/api/users?page=1", { username: 'Aamnah'});
3    let { data } = response.data;
4    this.setState({ users: data });
5}