0

How do I access the basket in other components like Navbar to show the contents of cart ? And please correct me if there is any logical errors in the code. Thanks in advance.

const cartReducer = (state, action) => {
    switch (action.type) {
        // other cases
        case 'INITIALIZE_CART':
            return action.payload;

        default:
            return state;
    }
};

const initialState = {
    basket: []
};

const CartContext = createContext();

const CartProvider = ({ children }) => {

    const [state, dispatch] = useReducer(cartReducer, initialState);

    useEffect(() => {
        axios.get('userdetails', {
            headers: { "Authorization": localStorage.getItem('token') }
        }).then(res => {
            console.log(res)
            dispatch({
                type: 'INITIALIZE_CART',
                payload: {
                    ...initialState,
                    basket: res.data.cart
                }
            })
        })
    }, []);

    return (
        <CartContext.Provider value={{ state, dispatch }}>
            {children}
        </CartContext.Provider>
    );
};

export const useStateValue = () => useContext(CartContext)

export default CartProvider
Siva
  • 21
  • 5
  • `state.basket` will be the data you can call `const [state, dispatch] = useReducer(cartReducer, initialState);` inside your component and take data from the state – Rahman Haroon Apr 07 '22 at 06:20

1 Answers1

0

import the CartState and use it for accessing state and passing action

import { CartState } from '../Cart/StateProvider'

const [{ basket }, dispatch] = CartState()
Siva
  • 21
  • 5