Comments (1)
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)
- Unexpected `revalidateIfStale = false` initial load behavior on key change HOT 1
- useSWR('key', fetcher) calls fetcher non-deterministically even when `key` is in the fallback
- Can I call both of onSuccess function in trigger options and useSWRMutation options?
- SWR should assert the data not be undefined if `isLoading` is false and `error` is null HOT 1
- Clarification Needed on Handling data for Optimistic Updates in useSWRMutation
- swr repeated render problem
- "isLoading" always true after clear the cache HOT 1
- Missing export of type `SWRInfiniteMutatorOptions` starting from 2.2.5
- Cache flaw: mutate of cache keys is ignored when no consuming hook is mounted
- Bound Mutate does not update state but useSWRMutation does HOT 2
- TYPESCRIPT: Axios fetcher(METHOD POST) + NextJs SSR = URL Malformed HOT 1
- Infinite does not revalidate all pages when the zeroth one changes HOT 2
- Conditional rendering does not have correct type
- Bound/global mutate functions do not mutate remote data HOT 2
- bug: type error on updating cache with bound mutate HOT 1
- RSC Example doesn't work HOT 6
- onDiscarded is never called
- TypeError: Cannot read properties of null (reading 'useContext') HOT 1
- useSWRInfinite with revalidateAll: true revalidates all pages when loading next page
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from swr.