Store data from useQuery with useState

夙愿已清 提交于 2020-05-15 07:54:08

问题


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)

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

回答1:


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

so this is another way of doing it:

const { loading, error, data } = useQuery(USER_QUERY, {onCompleted: setUserData})



回答2:


What are you trying to do with the returned data that you are unable to accomplish by simply using it as destructured from the query hook? In most use cases it can be used immediately, as it will update itself when refetched.

If it is necessary (and it could be), as the other answer says, the useEffect hook you posted should work, but I would replace the dependency with simply data, to prevent an edge case where the response has an equal length consisting of different data and does not update:

useEffect(() => {
  setUserData(data)
}, [data])


来源:https://stackoverflow.com/questions/57577102/store-data-from-usequery-with-usestate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!