使用 useState 存储来自 useQuery 的数据 [英] Store data from useQuery with useState
本文介绍了使用 useState 存储来自 useQuery 的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 React 钩子通过 react-apollo
获取 GraphQL 数据并存储本地状态:
I'm using React hooks both to fetch GraphQL data with react-apollo
and to store local state:
const [userData, setUserData] = useState({})
const { loading, error, data } = useQuery(USER_QUERY)
然而,我想知道如何将 data
存储到 userData
.这是它应该如何工作的:
However, I'm wondering how to store data
to userData
. Is this how it's supposed to work:
useEffect(() => {
setUserData(data)
}, [Object.entries(data).length])
推荐答案
看起来您所拥有的可能有效.options
参数中还有一个 onCompleted
选项.它需要一个回调类型:
Looks like what you have probably works. There is also a onCompleted
option available in the options
parameter. it takes a callback of type:
(data: TData | {}) => void
所以这是另一种方式:
const { loading, error, data } = useQuery(USER_QUERY, {onCompleted: setUserData})
这篇关于使用 useState 存储来自 useQuery 的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文