使用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)
但是,我想知道如何将数据
存储到 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屋!
查看全文