I am storing both username and password as key value async storage from main component.
In below component i am retrieving username and password from asyncstorage and stored as state and pass them to authentication for axios. But some how value received using state are always undefined. I have notice through logs that i am retrieving correct value from asyncstorage. So despite assigning value to usestate ,i am receiving undefined value.
when i store both username and password in a variable and passed to axios ,it does works.
Any help would be highly appreciated
function Home(props) {
const [username,setUsername]=useState();
const [password,setPassword]=useState();
const usernames ="abc";
const passwords="123";
const getData = async () => {
try {
const value1 = await AsyncStorage.getItem("login");
const value2 = await AsyncStorage.getItem("password");
setUsername(value1);
setPassword(value2);
console.log("retrieved value from async storage ",value1,value2 ); //both value are retrieved correctly
} catch (e) {
// error reading value
}
};
useEffect(() => {
getData();
console.log("stored value ",username,password ); // state value as undefined
axios
.post("https://........", {
auth: {
username:username,
password:password,
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}, [username,password]);
}
2
Answers
you aren’t calling
getData()
, also only do your axios request once the username and password have been set to truethy valuesA solution is to move the axios request inside another useEffect that only runs when the username and password are updated: