Search code examples
javascriptreactjscartuse-contextuse-reducer

How do I access data from useReducer(react) in other react-components?


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


Solution

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

    import { CartState } from '../Cart/StateProvider'
    
    const [{ basket }, dispatch] = CartState()