This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
I'm working on the authorization context for my project and somehow the authState won't update.
I expectat that when I log the authState in the async function I get the updated state but it simply doesn't. I tried wrapping it into aseperate function and call it inside the async function and even the useEffect but it makes no difference.
When I log the data from the API request I do get the requested information, I can log them like they are and I get the information I want. The problem is just in updating the state.
The async function is wrapped in a useEffect.
This is the state hook
const [authState, setAuthState] = useState({
user: {
username: '',
mail: '',id: ''
},
authStatus: 'pending'
})
const token = localStorage.getItem('token')
This is the useEffect
useEffect(() => {
const currentTime = new Date().getTime().valueOf() / 1000const
decodedToken = jwtDecode(token)
if (token) {
if (decodedToken.exp > currentTime) {
console.log(currentTime)
getUser()}
else {
setAuthState({
...authState,
user: '',
status: 'done'
})}}
}, [])
This is the async function
async function getUser() {
try {const {data} = await axios.get('url',
{headers: {"Content-Type": "application/json","Authorization": Bearer ${token},}})
setAuthState({...authState,
user:{username: data.username,mail: data.email,id: data.id},authStatus: 'done'})console.log(data)console.log(authState)}catch (e){console.error(e)}}
* Note that I did not include the actual url because it seemed like the right thing to do. The request itself works perfect.
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnprogra...