swr
swr copied to clipboard
fix: fix the type of the argument of `KeyedMutator` for `populateCache`
The Problem
I will show you the problem with this code sandbox. This container uses code sandbox introduced in swr docs with some changes.
I just added TypeScript and changed like below.
export async function addTodo(todo) {
await delay();
todos = [...todos, todo];
- return todos;
+ return todo;
}
In this codesandbox, there is an serious type error:
Argument of type 'Promise<ToDo>' is not assignable to parameter of type 'ToDo[] | Promise<ToDo[] | undefined> | MutatorCallback<ToDo[]> | undefined'.
Type 'Promise<ToDo>' is not assignable to type 'Promise<ToDo[] | undefined>'.
Type 'ToDo' is missing the following properties from type 'ToDo[]': length, pop, push, concat, and 25 more.
in the source code:
await mutate(addTodo(newTodo.text), {
optimisticData: [...(data ?? []), newTodo],
populateCache: (updatedTodo, todos) => [
...(todos ?? []),
updatedTodo,
],
revalidate: false,
});
I referred to this article.
In this article, the example written in JavaScript uses bound mutate
to make addToDo
return just one updated item, rather than multiple updated items.
However, when used in TypeScript like the codesandbox I suggested, this results in a type error.
For instance, when useSWR fetches an API that returns a ToDo[]
type, the first argument of mutate
is expected to be of type ToDo[]
.
This works fine in JavaScript, but the issue arises only when it's converted to TypeScript.
What this PR does
This PR fixes a type error problem related to populateCache
and bound mutate
.
Now, the first argument of bound mutate
only accepts a type of data fetched by useSWR
.
But in order to make use of populateCache
, the first argument of mutate
should accept any type of API fetching result.
So I changed the type of the first argument from Data
(which is the type of data useSWR
fetches) into MutationData
(which is the type of the data returned by the mutator)
In addition, I changed types in infinite
since it had error when I changed the type of KeyedMutator
.
This pull request is automatically built and testable in CodeSandbox.
To see build info of the built libraries, click here or the icon next to each commit SHA.