'React Native app needs to restart for AsyncStorage to work
I am currently working on a React Native app that uses AsyncStorage to store authentications tokens for users. I have a context to do this:
import React, { useReducer, createContext } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import jwtDecode from "jwt-decode";
const initialState = {
user: null,
};
AsyncStorage.getItem("user").then((res) => {
if (res !== null || res !== undefined) {
initialState.user = jwtDecode(res);
} else return;
});
const AuthContext = createContext({
user: null,
login: (userData) => {},
logout: () => {},
});
function authReducer(state, action) {
switch (action.type) {
case "LOGIN":
return {
...state,
user: action.payload,
};
case "LOGOUT":
return {
...state,
user: null,
};
default:
return state;
}
}
function AuthProvider(props) {
const [state, dispatch] = useReducer(authReducer, initialState);
function login(userData) {
AsyncStorage.setItem("user", userData.token);
dispatch({
type: "LOGIN",
payload: userData,
});
}
function logout() {
AsyncStorage.clear();
dispatch({ type: "LOGOUT" });
}
return (
<AuthContext.Provider
value={{ user: state.user, login, logout }}
{...props}
/>
);
}
export { AuthContext, AuthProvider };
My login function looks like this:
const [login, { error: loginError }] = useMutation(LOGIN_USER, {
update(_, { data: { login: userData } }) {
context.login(userData);
colorContext.setColor(
String(
_palette__colors[
Math.ceil(Math.random() * _palette__colors.length - 1)
]
)
);
navigation.reset({
index: 0,
routes: [{ name: "BottomTab" }],
});
},
variables: {
email,
password,
},
});
However, when I try to login the app returns and error saying that my "user" object is undefined. When I restart the app everything works fine, so it seems as if AsyncStorage needs to manually reload in order to load the data or something. Anyone knows how to resolve this error?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
