My reducer:
export const initialUserState = {
username: '',
address: '',
token: '',
address: '',
loggedIn: false,
loaded: false,
};
export const userReducer = async (state, action) => {
try {
switch (action.type) {
case 'LOAD':
try {
const value = JSON.parse(await AsyncStorage.getItem('user_info'));
const newState = { ...state, ...value, loggedIn: true, loaded: true };
console.log('New State:', newState);
if (value !== null) {
return newState;
}
} catch (error) {
return { ...state, loaded: true };
}
break;
default:
return state;
}
} catch (error) {
console.log(error);
return state;
}
};
My App.js:
import { userReducer, initialUserState } from './reducer';
const App = () => {
const [user, dispatch] = useReducer(userReducer, initialUserState);
useEffect(() => {
dispatch({ type: 'LOAD', ready: setReady });
}, []);
useEffect(() => {
console.log('state user:', user);
}, [user]);
}
export default App;
What happens is that in App.js, after the second useEffect is called, the state updates and user returns a promise. The promise has multiple properties, inside one of them is the correct state it was supposed to return. Shouldn't it return the state? Am I doing something wrong?
In a nutshell:
1) App starts
2) useEffect calls the first time and has the correct initial state
3) I call the LOAD action which will update the state
4) useEffect gets called the second time. This time it returns a promise, and it should return only the updated state of the store, I guess?
It looks like the function you pass to useReducer
is async
. All async
functions return a promise. You would need to await
or use .then
syntax to get the value from the promise. It's not a promise the first time through because it returns initial state. Hope that helps!