I am working on my first react-native app and I am in the process of developing the login page. I am using AsyncStorage to remember a user's token and log them in automatically. But it does not work and I get Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_asyncStorage.AsyncStorage.getItem'). here's my code:
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, FlatList, Image, Button, } from 'react-native';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { faStar } from '@fortawesome/free-solid-svg-icons'
import React, {useState, useEffect} from 'react'
import { TextInput } from 'react-native-gesture-handler';
import { AsyncStorage } from '@react-native-async-storage/async-storage';
export default function Login(props) {
const [ username, setUsername] = useState("")
const [ password, setPassword] = useState("")
useEffect(()=> {
getData();
}, [])
const auth = () => {
fetch(`http://192.168.5.213:8000/auth/`, {
method: 'POST',
headers: {
"Content-Type": 'application/json'
},
body: JSON.stringify({ username: username, password: password}),
})
.then( res => res.json())
.then( res => {
saveData(res.token)
props.navigation.navigate("MovieList")
})
.catch( error => console.log(error))
props.navigation.goBack();
}
const saveData = async (token)=> {
await AsyncStorage.setItem('Token', token)
}
const getData = async () => {
const token = await AsyncStorage.getItem('Token');
if(token) props.navigation.navigate("MovieList")
}
return (
<View style={styles.container}>
<Text style={styles.label}> Username</Text>
<TextInput
style={styles.input}
placeholder="Username"
onChangeText={ text => setUsername(text) }
value={username}
/>
<Text style={styles.label}> Password</Text>
<TextInput
style={styles.input}
placeholder="Password"
onChangeText={ text => setPassword(text) }
value={password}
secureTextEntry={true}
autoCapitalize={'none'}
/>
<Button onPress= {() => auth()} title="Login"/>
</View>
);
}
Login.navigationOptions = screenProps => ({
title: "Login",
headerStyle: {
backgroundColor: 'orange',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
fontSize: 24,
},
})
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
backgroundColor: '#282C35',
},
label: {
fontSize: 24,
color: "white",
padding: 10,
},
input: {
fontSize: 24,
backgroundColor: "white",
padding: 10,
margin: 10,
},
item: {
flex: 1,
padding: 10,
height: 50,
backgroundColor: '#282C35'
},
itemText: {
color:'#ffff',
fontSize: 24,
},
starContainer: {
alignItems: "center",
justifyContent: "center",
flexDirection: "row",
},
orange: {
color: 'orange',
},
white: {
color: 'white',
},
description: {
fontSize: 20,
color: 'white',
padding: 10,
},
});
How can I make this work?
CodePudding user response:
Try the default import
import AsyncStorage from '@react-native-async-storage/async-storage';
https://react-native-async-storage.github.io/async-storage/docs/usage