【问题标题】:How to deal with async data, React Context and hooks [duplicate]如何处理异步数据、React Context 和 hooks [重复]
【发布时间】:2021-10-11 08:08:51
【问题描述】:

在应用加载时,我正在获取存储在 Context 中的用户配置文件(使用 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 数据执行查询?

【问题讨论】:

    标签: reactjs asynchronous react-hooks apollo-client react-context


    【解决方案1】:

    您可以使用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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2020-07-08
      • 2020-06-06
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      相关资源
      最近更新 更多