Async await vs then

When working with API requests in React you can choose if you want to work with a promise syntax and make use of .then() or if you want to use async and await.

below are examples of both:

 onSearchSubmit(term) {
    axios
      .get("https://api.unsplash.com/search/photos", {
        params: { query: term },
        headers: {
          Authorization:
            "Client-ID MSiz2TTBQvP9bit6sPIO2GSHkgZ7X_vAk1f-nHc2Ru8",
        },
      })
      .then((response) => {
        console.log(response.data.results);
      });
  }

this code can be refactored by using async and await.

async onSearchSubmit(term) {
    const response = await axios.get("https://api.unsplash.com/search/photos", {
      params: { query: term },
      headers: {
        Authorization: "Client-ID Mxxxxx",
      },
    });
    console.log(response.data.results);
  }

Add your comment