Issue
I'm learning react native and I'm trying to figure out SecureStore. Why is it that when I logged in and successfully stored my user token in SecureStore, I can't use it again if I reload the screen using "RR". It does the same thing when I make changes to the code.
When I log the user object console.log(user), I see it, but I can't use it using the console.log(user.token). It comes up as undefined? IF I json.parse the user object, it works fine but I don't need to parse it when I initially logged in. What is the deal here and how can I keep using the object without parsing it first?
Here's the AuthProvider.js
LOG [AxiosError: Request failed with status code 401]
login: (email, password) => {
setIsLoading(true);
axiosConfig.post('login', {
email,
password,
device_name: 'mobile'
})
.then(response => {
const userResponse = {
token: response.data.token,
id: response.data.user.id,
name: response.data.user.name,
email: response.data.user.email,
avatar: response.data.user.avatar_url,
};
// communicate with backend and store token in secure store
setUser(userResponse);
setError(null);
SecureStore.setItemAsync('user', JSON.stringify(userResponse))
setIsLoading(false);
}).catch(error => {
// If the user haven't confirm the code. Show button to re-send the link
if(error.response.data.has_link){
setHasLink(true)
}
setError(error.response.data.message)
setIsLoading(false);
});
},
Here is the HomeStreen.jsx
axiosConfig.defaults.headers.common[
'Authorization'
] = `Bearer ${user.token}`;
axiosConfig
.get(`/my-animals?page=${page}`)
.then(response => {
// console.log(response.data);
if (page === 1) {
setAnimals(response.data.data);
} else {
setAnimals([...data, ...response.data.data]);
}
if (!response.data.next_page_url) {
setIsAtEndOfScrolling(true);
}
setIsLoading(false);
setIsRefreshing(false);
})
.catch(error => {
console.log(error);
setIsLoading(false);
setIsRefreshing(false);
});
Solution
Figured out my own question. I added a condition to check the user object in the useEffect hook and then parsing the object before passing it into the axios.
useEffect(() => {
if(user){
let userObj = JSON.parse(user);
setUser(userObj);
}
},[]);
Answered By - cueyouwhy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.