Reputation: 3
I have an User context provider where I want to store functions that validate and refresh his JWT token before every request.
Here is template of my code
const UserContext = createContext({})
const UserContextProvider = ({children}) => {
const [user, setUser] = useState(JSON.parse(localStorage.getItem("tokens")))
// set params for request
const getParams = (params) => {
return {
...params,
headers: {
...params.headers,
"Authorization": `Bearer ${user.access}`
}
}
}
// validate token
const validate = async () => {
return await fetch(url1, params1)
}
// refresh token
const refresh = async () => {
return await fetch(url2, params2)
}
// Authorized request. Token is validated, refreshed(if needed)
// and used in authorization header during fetch
const authFetch = async (url, params) => {
const valid = await validate()
if(valid){
return fetch(url, getParams(params))
}
else{
await refresh()
return fetch(url, getParams(params))
}
}
return (
<UserContext.Provider value={{user, setUser, authFetch}}>
{children}
</UserContext.Provider>
)
}
The problem is that authFetch function is not waiting for validation and refresh functions to complete and returned fetch sends undefined tokens to server.
How can I solve this?
Upvotes: 0
Views: 15