Search code examples
swrreact-suspensetime-limiting

React Suspense time limit


guys! I am relatively new to the concept of Suspense in React so i apologize if the question answer is obvious but i couldn't manage to find similar question asked before.

So i was wondering how can i set/simulate time limit for Suspense. Assuming i am having an API that returns a simple JSON after a 5 seconds dalay and i want Suspense to wait for 3s max then show some kind of ErrorComponent 'Time limit exceeded'?

Just to mention - i am fetching the data using SWR.

Thank you in advance!


Solution

  • I've tried to use loadingTimeout option and onLoadingSlow callback, but for some reason it does not fire when suspense: true. Maybe it is a bug.

    Another possible solution is to use something like axios to fetch the data, it has timeout option so you can specify this time limit after which axios will throw an error. Don't forget to disable swrs shouldRetryOnError option.

      const { data } = useSWR(
        `https://jsonplaceholder.typicode.com/posts/${post}`,
        // Use whatever timeout you need
        (url) => axios.get(url, { timeout: 5000 }),
        {
          suspense: true,
          shouldRetryOnError: false
        }
      );
    

    Edit https://stackoverflow.com/questions/73224251