Skip to content

Allow possibility to resolve data synchronously #155

Open
@Kaltsoon

Description

@Kaltsoon

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions