I'm new in React native
and I know this common to ask but I've been confused on how can I reflect varible to my view text based on the AsyncStorage
variable , I've used AsyncStorage
but it returns me an error
Error: Can't find variable:username
I have this
import React, {useContext,useState} from 'react';
import {
View,
Text,
StyleSheet,
ImageBackground,
} from 'react-native';
import {AuthContext} from '../navigation/AuthProvider';
import AsyncStorage from '@react-native-async-storage/async-storage';
const LoginScreen = ({navigation}) => {
const {googleLogin} = useContext(AuthContext);
const [state, setState] = useState(username);
AsyncStorage.getItem('userPrivilege').then((variable) => {
if (variable != null) {
console.log("hoy");
console.log(variable);
setState({username: variable})
}
});
return (
<View >
<ImageBackground source={require('../assets/images/launch_screen.png')} style= {styles.backgroundImage} >
<Text>{state.username}</Text>
</ImageBackground>
</View>
);
};
Update
It works now but when I tried to print value through a console it has infinite value in my console, do you know what the problem is?
Your error comes from an misunderstanding about how useState
works.
The value from the useState
, state
in your case takes the type of what you put inside, in your case username
in a string
or undefined
at the begging.
So state
is not an object
at the begging.
To fix your error, you can initialize your state to
const [state, setState] = useState({username: ''});
Update but it gets me an error
Objects are not valid as a React child(Found: object with keys {username}).If you meant to render a collection of children, use an array instead.
Code
const [state, setState] = useState({username: ''});
AsyncStorage.getItem('userPrivilege').then((variable) => {
if (variable != null) {
setState({username: variable})
}
}
return (
<View>
<Text>{state}</Text>
</View>
);
}
});