I’m developing my first app in react-native (expo). I did the flow of authentication and I’m using AsyncStorage to keep/manage the user info and jwt token.
I did the first window for the logged user but I couldn’t render the "Hello username" message.
First, I did this storage function to manage the user and token info:
import AsyncStorage from "@react-native-async-storage/async-storage";
const storage = () => {
const login = (user, jwt) => {
AsyncStorage.setItem("user", JSON.stringify(user));
AsyncStorage.setItem("authToken", `Bearer ${jwt}`);
};
const logout = () => {
AsyncStorage.removeItem("user");
AsyncStorage.removeItem("authToken");
};
const register = (user, jwt) => {
login(user, jwt);
};
const getUser = async () => {
const user = await AsyncStorage.getItem("user");
return JSON.parse(user);
};
const getAuthToken = async () => {
const token = await AsyncStorage.getItem("authToken");
return token;
};
return { login, logout, register, getUser, getAuthToken };
};
export default storage;
The component, that I called OverviewScreen looks like this:
import { Text } from 'react-native';
import React, { useEffect, useState } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import storage from '../utils/storage';
export default function OverviewScreen() {
const [user, setUser] = useState(null);
const { getUser } = storage();
useEffect(() => {
getUser().then((u) => {
setUser(u);
});
}, []);
return (
<SafeAreaView className="flex-1 items-center justify-center">
{!user ? (
<Text>Loading...</Text>
) : (
<Text>Hello {user.username}</Text>
)}
</SafeAreaView>)
}
I added a useEffect to print when user state change (if (user) console.log(user)
), and it is working fine. Also I tried to do the same behaviour writing the useEffect like this:
useEffect(() => {
const getUserAsync = async () => {
const u = await getUser();
setUser(u);
setIsLoading(false);
};
getUserAsync();
}, []);
And I obtained the same result.
Could someone help me? Thanks!
2
Answers
The problem was my fault.
The OverviewScreen was being rendered by a Tab.Screen and I used the prop children instead component to refer to it.
lets change
to
then see the result