I am using Context/Asyncstorage for state management. I store the data which returned from server to the Asyncstorage.
getData.then(
res => AsyncStorage.setItem('user', JSON.stringify(res.data))
)
And I set the global state named user in Global provider like below.
const [userState, userDispatch] = useReducer(
user, userInitialState,
async () => {
const storedUserData = await AsyncStorage.getItem('user');
return storedUserData != null ? JSON.parse(storedUserData) : userInitialState;
},
);
and Here is get the userState on other component
const SomeComponent = () => {
const {userState} = useContext(GlobalContext);
useEffect ( () => {
console.log(userState.name); // undefined
console.log(userState._W.name); // sammie (correct)
}, [])
return <View></View>
}
The problem is first console state return undefined because the userState looks like this
{
"_U": 0,
"_V": 1,
"_W": {
"name": "sammie",
"email": "sammie@test.com",
"phone": "123123123"
},
"_X": 0,
}
Expected value is
{
"_U": 0,
"_V": 0,
"_W": 0,
"_X": 0,
"name": "sammie",
"email": "sammie@test.com",
"phone": "123123123"
}
I tried with other state for the test. and when I set the state in useEffect hook like below, it returns like as above.
useEffect ( () => {
storeTheme('light')(themeDispatch); // store the light mode to the global theme state
}, [])
This theme state's data structure did not changed like as above. I am absolutely wired about this. Please give me some advice what I am wrong.
Thanks for any advise.
const [userState, userDispatch] = useReducer(
user, userInitialState,
async () => {
const storedUserData = await AsyncStorage.getItem('user');
console.log(storedUserData);
return storedUserData != null ? JSON.parse(storedUserData) : userInitialState;
},
);
Try logging the same as above and check the output. I feel like maybe the api team sent you the object this way.