Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!