I'm using useReducer with useContext to manage state, but I can't return initial value of state in a child component.
In my reducer file I have:
import context from './context';
const initialValue = {
case1token: null,
case2token: false,
};
const reducer = (state, action) => {
switch (action.type) {
case 'case1':
return {
case1token: action.payload,
};
case 'case2':
return {
case2token: action.payload,
};
default:
return initialValue;
}
};
export const {Provider, Context} = context(
reducer,
{
someFunction,
},
{initialValue},
);
In my context file I have :
import React, {useReducer} from 'react';
export default (reducer, actions, defaultValue) => {
const Context = React.createContext();
const Provider = ({children}) => {
const [state, dispatch] = useReducer(reducer, defaultValue);
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{state, ...boundActions}}>
{children}
</Context.Provider>
);
};
return {Context, Provider};
};
In my App.js file I can successfully return the case1token:
import {
Provider as AuthProvider,
Context as AuthContext,
} from './src/Context/auth/authContext';
function App() {
const {state} = useContext(AuthContext);
return (
<NavigationContainer ref={navigationRef}>
<View style={styles.root}>
<StatusBar barStyle="light-content" />
{state.case1token ? <MainFlow /> : <AuthFlow />}
</View>
</NavigationContainer>
);
}
export default () => {
return (
<AuthProvider>
<App />
</AuthProvider>
);
};
In this file I'm trying to return the case2token but it's only returning case1token:
import {Context as AuthContext} from '../../Context/auth/authContext/';
const Home = () => {
const {state} = useContext(AuthContext);
console.log(state);
return (
<SafeAreaView style={styles.screen}>
<Header/>
<Text>{state.case2token}</Text>
</SafeAreaView>
);
};
When I log in App.js both tokens get returned.
Why isn't it returning in the child component?
Appreciate any help!