Now that mutate support passing an async function to get the data it will be helpful to get that data as return value of mutate.
const data = await mutate('/api/data', fetch('/api/data').then(res => res.json()))
// use data
This way if I want to use the data right now for something else I don't need to use the old way of first fetch and await and then pass the data to mutate and return it below.
const data = await fetch('/api/data').then(res => res.json());
mutate('/api/data', data)
// use data
Good suggestion 馃憤 That was what we wanted to do too.
And I think it would be great to do this together with #136 in v0.2 to have a more general, unified API. We will probably merge revalidate and mutate (maybe it needs to be renamed):
const { mutate } = useSWR(...)
// it supports:
mutate() // revalidate
mutate(newData) // update data
mutate(newData, false) // update data + no revalidation
mutate(promise) // update data from a promise
mutate(promise, false) // update data from a promise + no revalidation
mutate(data => newData) // update data from a function
mutate(data => newData, false) // update data from a function + no revalidation
mutate(async data => await getData()) // update data from an async function
mutate(async data => await getData(), false) // update data from an async function + no revalidation
const res = await mutate(...) // return the data
Same for the global import { mutate } from 'swr', it requires a key as the first parameter and everything else will stay the same.
I think would be nice to have this interface as well:
mutate(key, data => { ...data, [newId]: newData })
I think would be nice to have this interface as well:
mutate(key, data => { ...data, [newId]: newData })
would this new API allow us to essentially mutate an endpoint that was fetched from an adjacent component? for example:
<TodoList A /> :
const {data: todos} = useSWR('key1')
const addTodo = (todo) => {
mutate('key1', [...todos, todo]);
mutate('key2', (todoListBtodos) => [...todoListBTodos, todo]);
}
<TodoList B />:
const {data: todos} = useSWR('key2');
Yeah, you should be able to mutate any key used in your app even if you don鈥檛 have the current data in the scope of your mutate call.
Most helpful comment
I think would be nice to have this interface as well: