Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda