Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda