swr icon indicating copy to clipboard operation
swr copied to clipboard

key has change, never revalidate

Open j-xzy opened this issue 3 years ago • 5 comments

Bug report

Description / Observed Behavior

version: 1.0.1, key has change, never revalidate

Repro Steps / Code Example

CodeSandbox

Context

https://github.com/vercel/swr/pull/1430#issuecomment-928890102

j-xzy avatar Oct 06 '21 02:10 j-xzy

I think this should be the correct behavior of revalidateOnMount: false. When the key changes, it should not automatically revalidate if revalidateOnMount is manually disabled.

shuding avatar Oct 13 '21 05:10 shuding

@shuding I had a similar issue I want to only revalidate if the key changes but otherwise never revalidate. What combination of options should I use?

GeraldHost avatar Jan 05 '22 16:01 GeraldHost

@shuding I had a similar issue I want to only revalidate if the key changes but otherwise never revalidate. What combination of options should I use?

GeraldHost avatar Jan 05 '22 16:01 GeraldHost

I have the same problem, I don't want revalidateOnMount but I need revalidateOnKeyChange.

Can you add the new config revalidateOnKeyChange?

More clear, I want using useSWRImmutable and can revalidateOnKeyChange to be true

How can SWR meet my requirement?

Thanks!

I can code like below, but I really want it have officially config to achieve. if not using useEffect, it won't revalidate if key change back to 'firstKey'

import React, { useEffect, useState, useRef } from "react";
import useSWRImmutable from "swr/immutable";

function fetcher() {
  console.log("revalidate!");
  return 'value';
}

function Test() {
  const [key, setKey] = useState('firstKey');
  const mountedRef = useRef(false);
  const { mutate } = useSWRImmutable([key], fetcher);

  useEffect(() => {
    if (mountedRef.current === false) {
      mountedRef.current = true;
      return;
    }

    mutate();
  }, [mutate, key]);
  return (
    <div>
      <button
        onClick={() => {
          setKey('secondKey');
        }}
      >
        secondKey
      </button>
      <button
        onClick={() => {
          setKey('firstKey');
        }}
      >
        firstKey
      </button>
    </div>
  );
}

filenwind avatar Jan 17 '22 10:01 filenwind

Reopened the issue since the following should be the correct behavior. When the key changes, useSWRImmutable should definitely refetch.

More clear, I want using useSWRImmutable and can revalidateOnKeyChange to be true

shuding avatar Jan 20 '22 01:01 shuding

Is this still an active bug?

caydgreen avatar Mar 15 '23 19:03 caydgreen

here is the reproduce

You can switch key by click each button, and see the revalidate log.

It won't revalidate if key already fetched, so I want a config like revalidateOnKeyChange

I don't know this is a bug or not.

filenwind avatar Mar 21 '23 08:03 filenwind