let initialData = {
products:[]
}
const ItemReducer = (state = initialData, action) => {
switch (action.type) {
case "FETCHDATA":
return {
...state,
products: action.payload,
};
}
return state;
}
let [productdata, setProductdata] = useState();
const dispatch = useDispatch();
useEffect(()=>{
axios.get("https://fakestoreapi.com/products")
.then((res) => setProductdata(res.data))
.catch((err) => console.log("error"))
},[]);
dispatch({type:"FETCHDATA",payload: productdata});
Initial state of ItemReducer must contain the "product details" which needs to be fetch from api call. While am using the above code, its returning undefined.
2
Answers
One possibility is to do the fetch in a parent component and only render the children (that has the
useDispatch
) when the productData is present. That way it can also handle error and loading states, something like this:Related to the docks you have to use