简体   繁体   中英

useContext returning undefined when using hook

So I am trying to create a kind of store using react context API and I ran into a problem that when I use the useContext it is returning undefined. So the code I have is this:

StateProvider.js

import React, { createContext, useContext, useReducer } from "react";

//Needed to track the basket and the user info

//DATA LAYER
export const StateContext = createContext();

// BUILD PROVIDER
export const StateProvider = ({ reducer, initialState, children}) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
);

export const useStateValue = () => useContext(StateContext);

reducer.js

export const initialState = {
    basket: ["asd", "asd"],
};

function reducer(state, action) {
    switch(action.type){
        case 'ADD_TO_BASKET':
            //add item to basket
            break;
        case 'REMOVE_FROM_BASKET':
            //remove item from basket
            break;
        default:
            return state;
    }
}

export default reducer;

index.js

import reducer, { initialState } from './state/reducer';
....

<StateProvider initalState={initialState} reducer={reducer}>
      <App />
</StateProvider>

And the problem is on this file, where I try to console log the basket that I get from the reducer.js initalState.

Header.js

import { useStateValue } from '../state/StateProvider'
...
function Header() {
    console.log(useContext(StateContext))
    const [{ basket }]= useStateValue();
    console.log(basket);

So the error is when I use the const [{ basket }]= useStateValue(); , it says this: Cannot read property 'basket' of undefined.

The problem was on index.js, initialState was badly written and I was getting no error because of ES6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM