On App load, I am fetching the user profile (with Apollo query hook) that I store in the Context.
const AuthContext = createContext()
export const AuthProvider = ({ children }) => {
const user = useQuery(GET_PROFILE)
return (
<AuthContext.Provider value={user}>
{children}
</AuthContext.Provider>
)
}
export const useAuth = () => {
return useContext(AuthContext)
}
Then I have a custom hook that will call the context to retrieve user information. I am using the result right away as a query parameter (the query is executed as soon as the hook is called)
export const useProject = () => {
const user = useAuth()
console.log('Current project ID', user?.currentProjectId) // undefined
const data = useQuery(
GET_PROJECT, {
variables: {
projectId: user?.currentProjectId // Error: Variable "$projectId" of required type "ID!" was not provided.
}
}
)
return data
}
The problem is user
is used as before the data is available.
If the data was used in a presentational component, I would use a Loader or Suspense but how can I make it work inside a hook? How can I make sure the query is executed with the user
data available?