0

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?

eakl
  • 501
  • 8
  • 22

1 Answers1

1

You can use the skip parameter to disable the query when a certain condition is not met. In this case, if the user variable is not defined.

export const useProject = () => {
  const user = useAuth()

  const data = useQuery(
    GET_PROJECT, {
      skip: !user,
      variables: {
        projectId: user?.currentProjectId // Error: Variable "$projectId" of required type "ID!" was not provided.
      }
    }
  )

  return data
}
Chris
  • 6,331
  • 1
  • 21
  • 25