'How to solve async-await function problem while using Axios?

I want to use axios using async await function.

But when I use async await function then I get an error.

useEffect(async() => {
   await axios
        .get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
        .then((data) => setItems(data.data));
}, []);


Solution 1:[1]

You are using both promises and async/await at the same time either use .then() or use async/await: Here I have shown how you can do this using promises:

useEffect(async() => {
axios.get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
  .then(function (response) {
    setItems(response.data);
  })
  .catch(function (error) {
    console.log(error);
  })}, [])

Here I am using async await:

useEffect(async() => {
    let response = await axios.get("https://cryptic-inlet- 
    27003.herokuapp.com/products?size=6")
    setItems(response.data);
}, [])

Solution 2:[2]

You can't use a async await inside of useEffect because that is not a methodologic of react, you have that change your logic code to other, for example use useState varaibles and with the result of axios you will update the useState varaibles, something like that:

const [items, setItems]=useState({})//any

useEffect(async() => {
   axios
        .get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
        .then((data) => setItems(data.data));
}, []);

useEffect(()=>{
  console.log(items, 'this items changed')
  //to do...
}, [items])

or

const [items, setItems]=useState({})//any

async function requestAxios(){
  const data=await axios.get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
  setItems(data.data)
}

useEffect(async() => {
   requestAxios()
}, []);

useEffect(()=>{
  console.log(items, 'this items changed')
  //to do...
}, [items])

Solution 3:[3]

The issue is that you're using promises and async/await at the same time. Async/await is nothing but sugar coating of promises. You can read more about promises here.

const fetchData = async () => {
  const { data } = await axios.get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
   // do something with data!
};
useEffect(async() => {
  fetchData();
}, []);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SonickSeven
Solution 3