Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: Is it OK to map over AtomWithQueryResult? #79

Open
emccorson opened this issue Apr 25, 2024 · 1 comment
Open

Question: Is it OK to map over AtomWithQueryResult? #79

emccorson opened this issue Apr 25, 2024 · 1 comment

Comments

@emccorson
Copy link

emccorson commented Apr 25, 2024

I couldn't find anywhere else to ask this, so sorry in advance if this is the wrong place.

I'd like to be able to apply a function to the data part of an AtomWtihQueryResult value. I have the following implementation, which I think works fine, but are there any reasons I am missing why this would not work or is a bad idea?

const mapQueryResult = <A,B,E>(
  f: ((a: A) => B),
  queryResult: AtomWithQueryResult<A, E>
): AtomWithQueryResult<B, E> => {
  if (queryResult.isSuccess || queryResult.isRefetchError) {
    return {
      ...queryResult,
      data: f(queryResult.data),
      refetch: (...args) => queryResult.refetch(...args).then(res => mapQueryResult(f, res))
    };
  } else {
    return queryResult;
  }
};
@kalijonn
Copy link
Collaborator

Nothing is obviously bad to me about that implementation. But if you only want to transform data, you can either use a derived atom, or use the select property available in useQuery: https://tanstack.com/query/latest/docs/framework/react/reference/useQuery

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

No branches or pull requests

2 participants