Reputation: 13
Context.js
import axios from "axios";
import React, {
createContext,
useContext,
useEffect,
useReducer,
useState,
} from "react";
import { cartReducer } from "./Reducer";
const Cart = createContext();
const Context = ({ children }) => {
const [products, getProduct] = useState("");
useEffect(() => {
axios.get("/api/products/").then((response) => {
getProduct(response.data);
});
}, []);
console.log(products);
const [state, dispatch] = useReducer(cartReducer, {
products: products,
cart: [],
});
console.log(state);
return <Cart.Provider value={{ state, dispatch }}>{children}</Cart.Provider>;
};
export default Context;
export const cartState = () => {
return useContext(Cart);
};
I successfully called axios.get and console log the value of products and it has all the products in it, but when I try to pass it in useReducer and try to log the state it shows empty array.
Reducer.js
export const cartReducer = (state, action) => {
switch (action.type) {
default:
return state;
}
};
Upvotes: 1
Views: 42
Reputation: 31
const [state, dispatch] = useReducer(cartReducer, {
products: products,
cart: [],
});
useReducer only need products for initail the state it will be not updated just because you update products with useState;
And you are keeping the state in both useState and useReducer you should be using only one.
if you use useReducer then
action structure should {type,payload}
const [state, dispatch] = useReducer((pervState,action)=>{
switch(action.type){
case "setProducts":
return {...prevState,products:action.payload};
case "setCart":
return {...prevState,cart:cart.payload};
default:
throw new Error(`unhandled action.type ${action.type}`)
}
},{
products: products,
cart: [],
});
Upvotes: 1