'getting data from function in context
i want to return data that come from api. my function is in context an i want it to return data than i restore it in my component (not in context) . and my problem is that my state (product) in component does not update. and this is my code .
my function in context
const getFilteredProducts = async (field,value,operator) => {
try {
dispatch({type: "IS_LOADING"})
const response = await fetch(
`http://localhost:1337/api/products?populate=*&filters[${field}][${operator}]=${value}`,
{
method: "GET",
headers : {
'content-type' : 'application/json'
}
})
if (!response.ok) {
console.log(response)
throw new Error('Something went wrong!');
}
const data = await response.json();
const readyData = [];
for (const key in data.data){
readyData.push({
id: key,
img: data.data[key].attributes.img,
name: data.data[key].attributes.name,
description: data.data[key].attributes.description,
featured: data.data[key].attributes.featured,
price: data.data[key].attributes.price,
})
}
console.log(readyData)
return readyData;
}catch (error){
alert(error)
}
dispatch({type: "IS_NOT_LOADING"})
}
my code in component
import React, {Fragment, useContext, useEffect, useState} from "react";
import ProductList from "./ProductList";
import ProductContext from "../../store/product-context";
import Loading from "../Loading";
export default function FeaturedProducts() {
const productCtx = useContext(ProductContext);
const [products,setProducts] = useState([]);
useEffect(() => {
setProducts(productCtx.getFilteredProducts('featured',true,"$eq"));
},[])
console.log(products)
return(
<Fragment>
{productCtx.isLoading ? <Loading/> : <ProductList products={products}/>}
</Fragment>
)
}
Solution 1:[1]
Try to move the dispatch({ type: 'IS_NOT_LOADING' }); line before the return statement in your getFilteredProducts function:
for (const key in data.data) {
readyData.push({
id: key,
img: data.data[key].attributes.img,
name: data.data[key].attributes.name,
description: data.data[key].attributes.description,
featured: data.data[key].attributes.featured,
price: data.data[key].attributes.price,
});
}
console.log(readyData);
dispatch({ type: 'IS_NOT_LOADING' }); // <- Update the state before returning
return readyData;
} catch (error) {
alert(error);
}
};
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 | lpizzinidev |
