GithubHelp home page GithubHelp logo

Comments (1)

ConsoleTVs avatar ConsoleTVs commented on June 22, 2024

This likely happens due promise catching. The only way I've found to invalidate the cache is to change the key of the SWR hook. The example below uses an array as the key but you may also use other data structures, or even the same url with different query params. In the end, you have to invalidate the last key. Think of it as a useMemo(promise, [key]).

The following solution refetches the exact same url by using an array instead of a different url string:

import {
  PropsWithChildren,
  Suspense,
  createContext,
  useContext,
  useState,
} from "react";
import { ErrorBoundary, FallbackProps } from "react-error-boundary";
import useSWR, { SWRConfig, SWRConfiguration } from "swr";

async function fetcher(key: string | [string, string]) {
  const url = Array.isArray(key) ? key[1] : key;

  console.log("fetching", key, url);
  const response = await fetch(url);

  if (!response.ok) {
    throw new Error("Failed to fetch");
  }

  return await response.json();
}

function User() {
  const key = useContext(KeyContext);
  const { data } = useSWR(() => [
    key,
    `https://jsonplaceholder.typicode.com/users/1222`,
  ]);

  return <div>{data?.name}</div>;
}

const config: SWRConfiguration = {
  fetcher,
  suspense: true,
};

const KeyContext = createContext<string>("");

function SafeSuspense({ children }: PropsWithChildren) {
  function random(): string {
    return Math.random().toString(36).slice(2, 7);
  }

  const [key, setKey] = useState(random());

  function reset({ error, resetErrorBoundary }: FallbackProps) {
    function resetBoundary() {
      setKey(random());
      resetErrorBoundary();
    }

    return (
      <>
        <div>{error.toString()}</div>
        <button onClick={resetBoundary}>Retry</button>
      </>
    );
  }

  return (
    <ErrorBoundary fallbackRender={reset}>
      <Suspense fallback={<div>Loading</div>}>
        <KeyContext.Provider value={key}>{children}</KeyContext.Provider>
      </Suspense>
    </ErrorBoundary>
  );
}

function App() {
  return (
    <SWRConfig value={config}>
      <SafeSuspense>
        <User />
      </SafeSuspense>
    </SWRConfig>
  );
}

export default App;

What can we do?

I would advise to have this functionality internally in SWR. I would advice to have a key/id in the memo dependency list that came from a context. That way, you could expose a invalidate() or invalidate(key) so that people could use it in their error boundaries. I am not sure if this solution suits the internals of SWR but for sure it does the trick here.

from swr.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.