Description
Would it be possible to somehow provide Async
and useAsync
a way to resolve data synchronously? This would allow the use of any synchronous caching solution and eliminate rerenders caused by status updates. At the current state of the library, I have only come up with a solution that memoizes the promiseFn
function, however it is still asynchronous.
This might not be the best API, but for the sake of an example case:
const useTodo = todoId => {
const todoClient = useTodoClient();
const cache = useCache();
const { data, ...rest } = useAsync({
promiseFn: todoClient.getById,
cacheFn: ({ id }) => cache.get(`todo.${id}`), // Synchronous way to resolve the data
id: todoId,
watch: todoId,
});
return { todo: data, ...rest };
};
Optional cacheFn
argument would introduce a way to resolve data synchronously and it should be the primary way to resolve the data (secondary would be to use the good old promiseFn
). This way no additional renders are required in case the fn
function can resolve the data (it returns something else than undefined
). cacheFn
function would receive the same arguments as the promiseFn
function.
Because this solution is quite flexible, we could easily disable cache by conditionally providing the cacheFn
function:
useAsync({
promiseFn: todoClient.getById,
cacheFn: cacheEnabled ? ({ id }) => cache.get(`todo.${id}`) : undefined,
id: todoId,
watch: todoId,
});
If this can be done another way, without introducing a new argument I would gladly hear about it.
Edit: Renamed fn
to cacheFn
, because it describes the usage better.