如何处理异步数据、React Context 和 hooks

How to deal with async data, React Context and hooks

在应用程序加载时,我正在获取我存储在上下文中的用户配置文件(使用 Apollo 查询挂钩)。

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)
}

然后我有一个自定义挂钩,它将调用上下文来检索用户信息。我立即将结果用作查询参数(调用钩子后立即执行查询)

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
}

问题是 user 在数据可用之前使用。

如果数据用于展示组件,我会使用 Loader 或 Suspense,但我怎样才能让它在挂钩中工作?如何确保查询是在 user 数据可用的情况下执行的?

您可以使用skip参数在不满足某个条件时禁用查询。在这种情况下,如果用户变量没有定义。

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
}