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));
}, []);
CodePudding user response:
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);
}, [])
CodePudding user response:
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 } = axios.get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
};
useEffect(async() => {
fetchData();
}, []);
CodePudding user response:
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])