I start to use React Native, and should use AsyncStorage instead of LocalStorage
But I can't deal with async in useEffect and AsyncStorage, because token sets after fetch send everything. Help me please with that
const [tkn, setTkn] = useState('')
const getData = async () => {
try {
const value = await AsyncStorage.getItem('token')
if(value !== null) {
setTkn(value)
}
} catch(e) {
}
}
useEffect(() => {
AsyncStorage.getItem('token').then((value) => {
if (value) {
setTkn(value)
}
});
fetch('http://127.0.0.1:8000/home', {
method: "GET",
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Token': tkn
}
})
.then(function (response) {
if (response.status >= 200 && response.status <= 299) {
return response.json();
} else {
}
})
.then(funds => {
///
}).catch(function (error) {
})
}, [history])
I would recommend creating two effects: one to fetch the token from storage, and one to make the API call.
The first effect will fire when the component mounts (pass a []
as the useEffect dependencies) and the second will fire when the token changes (pass [tkn]
to that useEffect, and check to make sure that the token has a non-empty value).
This way, you won't have to worry about chaining all of your async logic together.