How can I use the useQuery hook to populate state in other hooks?

前端 未结 2 795
情深已故
情深已故 2021-02-09 04:48

I have been dealing with a few hook-related issues recently as I have been implementing hooks into a project of mine. I keep getting the error \"Rendered more hooks than during

相关标签:
2条回答
  • 2021-02-09 05:27

    What you need to do is to update the state when the first hook results in a response. To do that you can make use of useEffect hook. You need to render all hooks at the top of your functional component.

    const [url, setUrl] = useState('')
    
    const updateLink = useMutation(LINK_UPDATE_MUTATION, {
      variables: {
        id: props.id,
        url
      }
    })
    
    const { data, loading, error } = useQuery(LINK_QUERY, {
      variables: {
        id: props.id
      }
    })
    
    useEffect(() => {
      if(data && data.link) {
        setUrl(data.link.url);
      }
    }, [data])
    
    if (loading) {
      return <div>Loading...</div>
    }
    if (error) {
      return <div>Error! {error.message}</div>
    }
    
    0 讨论(0)
  • 2021-02-09 05:35

    You can simply follow this apprch, I also did by this way.

      const client = useApolloClient();
      const [newData, setNewData] = useState(null);
      const [loading, setLoading] = useState(false);
    
      async function runQuery() {
        setLoading(true);
    
        const useQueryData = await client.query({
          query: SUBMITTED_ASSIGNMENTS, variables: {
            userId
          }
        });
        setNewData(useQueryData?.data?.assignments);
        console.log('newData', newData);
        setLoading(false);
      }
    
      useEffect(() => {
        runQuery();
      }, [newData]);
    
    0 讨论(0)
提交回复
热议问题