It is exactly as the title says. I know this is a popular problem, but none of the solutions i have seen have worked for me.
My reducer
export const productDetailsSLice = createSlice({
name: "productDetails",
initialState: {
product: {},
error: null,
loading: false,
},
reducers: {
getProductDetail(state, action) {
// Object.assign(state, action.payload);
state.loading = action.payload.loading;
state.product = action.payload.product;
state.error = action.payload.error;
},
},
});
My action
export const productDetailAction = async (dispatch, productDetail, id) => {
dispatch(
getProductDetail({
loading: true,
product: {},
error: null,
})
);
await fetch(`/api/products/${id}`, {
method: "GET",
headers: {},
})
.then((response) => {
if (!response.ok) {
return response.json().then((data) => {});
} else {
return response.json().then((data) => {
dispatch(
getProductDetail({
loading: false,
product: data,
error: null,
})
);
});
}
})
.catch((error) => {
dispatch(
getProductDetail({
loading: false,
product: productDetail.product,
error:
error.response && error.response.data.detail
? error.response.data.detail
: error.message,
})
);
});
};
My component
const productDetails = useSelector((state) => state.productDetails);
const { error, loading, product } = productDetails;
useEffect(() => {
if (!product.name || product._id !== Number(productId)) {
productDetailAction(dispatch, productDetails, productId);
}
}, [product]);
when i console.log(product) it is undefined but i can see that my API call was sent successfully and indeed my redux state has changed. retrieving the new value is the problem. Please help!! stuck on this for a long time now. Thank you