Skip to content

Conversation

@kelleyvanevert
Copy link

@kelleyvanevert kelleyvanevert commented Feb 15, 2020

This is a little example implementation of the mutateMany feature request described in Issue #264.

(Note: not necessarily meant to be merged, at least not without some good inspection etc. The tests pass on my machine, but I can't be sure I've understood the full ramifications of the addition, so definitely more eyes and work would probably be needed to make it stable and work exactly as it should. I updated the cacheSet / cacheGet functions a bit, which lie at the heart of the whole operation... so that's a bit scary. Also, this is the first time I'm contributing to an open source project like this, so this is new to me :))

Example usage

import React, { useState } from "react";
import useSWR, { mutateMany } from "swr";

const fetcher = (url: string) => fetch(url).then(r => r.json());

export default function App() {
  const [newTitle, setNewTitle] = useState("");

  const reqs = ["100", "200", "300"].map(num => {
    return useSWR(`https://xkcd.now.sh/?comic=${num}`, fetcher);
  });

  const mutateMultipleTitles = () => {
    mutateMany(key => {
      if (/comic=(100|200)/.test(key + "")) {
        return {
          update(comicInfo: any) {
            return {
              ...comicInfo,
              title: newTitle
            };
          },
          shouldRevalidate: false
        };
      }
    });
  };

  return (
    <div>
      <p>
        <input value={newTitle} onChange={e => setNewTitle(e.target.value)} />{" "}
        <button onClick={mutateMultipleTitles}>Change first two titles</button>
      </p>
      {reqs.map(({ error, data }, i) => {
        return (
          <div key={i}>
            {error ? (
              <p>Error</p>
            ) : !data ? (
              <p>Loading...</p>
            ) : (
              <pre>{JSON.stringify(data, null, 2)}</pre>
            )}
          </div>
        );
      })}
    </div>
  );
}

Typing

Also, typing mutateMany well is quite the challenge :) Something to do with the non-existence of existential types in TypeScript I think. So this implementation doesn't even try, but maybe with some trick it could be gotten to work?

@FrankFang
Copy link

I like this api.

@sergiodxa
Copy link
Contributor

I published a lib to do this with a similar implementation under https://www.npmjs.com/package/swr-mutate-many

@shuding
Copy link
Member

shuding commented Jun 30, 2021

Closing as we've landed the new Cache API that covers this use case 👍, docs: https://swr.vercel.app/advanced/cache#mutate-multiple-keys.

@shuding shuding closed this Jun 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants