Skip to content

Instantly share code, notes, and snippets.

@zecka
Created May 26, 2025 19:10
Show Gist options
  • Save zecka/570f116033c4ed63ed92c9a5e4fff980 to your computer and use it in GitHub Desktop.
Save zecka/570f116033c4ed63ed92c9a5e4fff980 to your computer and use it in GitHub Desktop.
SWR Mutation without api revalidation:
/**
* @see: https://stackoverflow.com/questions/72757228/mutate-useswr-data-local-state-without-revalidating
*/
import React from "react";
import useSWR from "swr";
const fetcher = async (url) => {
await new Promise(resolve => setTimeout(resolve, 1000));
return fetch(url).then((res) => res.json())
};
export default function App() {
const { data, error, isLoading, mutate } = useSWR(
"https://api.github.com/repos/vercel/swr",
fetcher
);
const handleMutate =()=>{
mutate(
{ ...data, subscribers_count: 1222 },
{ revalidate: false }
)
}
if (error) return "An error has occurred.";
if (isLoading) return "Loading...";
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<button onClick={handleMutate}>Test</button>
<strong>👁 {data.subscribers_count}</strong>{" "}
<strong>✨ {data.stargazers_count}</strong>{" "}
<strong>🍴 {data.forks_count}</strong>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment