0

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?

2
  • I think this could slow down your application a lot, why not decouple refreshing from your regular API calls and have your token refresh on page load with a useEffect or something? Commented Jul 27, 2023 at 23:57
  • @fordat Your approach seems to be much better than my, thanks! Commented Jul 29, 2023 at 10:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.