apollographql / react-apollo

:recycle: React integration for Apollo Client
https://www.apollographql.com/docs/react/
MIT License
6.85k stars 787 forks source link

useQuery hook fetches data twice #3906

Open Zver64 opened 4 years ago

Zver64 commented 4 years ago

Intended outcome: Get data from graphql server provided by graphql documentation using useQuery hook from @apollo/react-hooks

Actual outcome: The data is fetched twice instead of once.

How to reproduce the issue: I have created a simple react app in codesandbox that you can open up using the link below: https://codesandbox.io/s/infallible-pasteur-wq3zp Here is the screenshot of my logs. You can see that the data object is returned twice: image

I have also tried to use apollo/client from beta docs, but the result is the same.

Version

System: OS: Windows 10 10.0.19587 Binaries: Node: 12.16.0 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.13.4 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: 44.19587.1000.0 npmPackages: apollo-boost: ^0.4.7 => 0.4.7

dylanwulf commented 4 years ago

The console.log statement may be running twice, but your data is only being fetched once. If you look at the Network tab in your browser's dev tools then you'll see that there's only one request being made to 48p1r2roz4.sse.codesandbox.io. The reason the console.log statement is running twice is because you have it set up to call console.log every time TestComponent renders, and it renders twice after receiving data.

Zver64 commented 4 years ago

Thank you for your responce @dylanwulf ! Is it a normal behavior for a component to render twice? I was expecting it to render once...

dylanwulf commented 4 years ago

The extra render might not be necessary in your case, but apollo-client is probably updating some other values that you're not reading and that's why you see it render a second time. An extra render will not affect the appearance of your component at all, and should be negligible in terms of performance.

Zver64 commented 4 years ago

It looks like it only works because of caching...If I try to send a unique request for each render - I end up having an infinite number of requests. And I also found out that I cannot disable cache by setting no-cache fetch policy.

Nisfan commented 4 years ago

Same issue for me as well, I am able to see four console logs

image

and last one is

image

dane-stevens commented 4 years ago

I'm seeing duplicate renders as well. Both renders happen after query loading has finished.

sirldev commented 4 years ago

Isn't this problem related to ?

dane-stevens commented 4 years ago

@JunHyeokHa it is indeed! Thank you!

mohammed-shameem commented 4 years ago

Any workaround for this?. rendering twice is causing issues in infinite scroll

Zver64 commented 4 years ago

@mohammed-shameem As @JunHyeokHa mentioned the problem is related to React Strict mode. So you can disable it, if it is not necessary for your project.