brillout / react-streaming

React Streaming. Full-fledged & Easy.
MIT License
220 stars 14 forks source link

Infinite loop when fetching data with `useAsync()` #9

Closed jaybe78 closed 2 years ago

jaybe78 commented 2 years ago

I'm using client routing in vps, and when switching to a page that has a component with useAsync(), I can see in useSsrData, that (obviously) it creates a new key that is different than the initial key created at first load(server side).

Thus, the data in the html tree is never found, then creates a new promise, throws the state, that triggers the update of suspense, which triggers the update of the wrapped component, and so there's an infinite loop... :

UseAsync client side if id has not been created server side

  1. Creates new ID
  2. Id not found
  3. New promise
  4. Update promise State 'pending'
  5. Result: Component unmount/mount
  6. Go back to 1

I think the documentation should make it clear, that useAsync only works when you are coming from the server, so only for server routing, otherwise only useSSRData is indicated with a static id.

https://user-images.githubusercontent.com/3605098/171516199-4526eb50-97f2-4149-8adf-60845ab3ea68.mov

Steps: 1) Click on About 2) Go back to Home 3) Result: infinite loop

I tried with react-router as well using the example you added in vite-plugin-ssr. I get the same issue this time on first load. https://github.com/jaybe78/vps-webpack5-redux-streaming-test/pull/1/files

Though I confirm in both cases it works, if I replace

const movies = useAsync(async () => {
    const response = await fetch(
      "https://star-wars.brillout.com/api/films.json"
    );
    return response.json();
  });

by

const movies = useSsrData('movies', async () => {
    const response = await fetch(
      "https://star-wars.brillout.com/api/films.json"
    );
    return response.json();
  });
brillout commented 2 years ago

It should actually work with Client Routing.

Reproduction is welcome and I'll have a look.

jaybe78 commented 2 years ago

@brillout Done ! Thanks

brillout commented 2 years ago

I could reproduce, I'll have a look at it tomorrow.

brillout commented 2 years ago

It's a React bug: https://github.com/facebook/react/issues/24669.

jaybe78 commented 2 years ago

Oh sh*t! . I guess I'll stick to static id for now. Thanks @brillout.