Giter VIP home page Giter VIP logo

tanstack / query Goto Github PK

View Code? Open in Web Editor NEW
39.7K 198.0 2.7K 51.9 MB

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.

Home Page: https://tanstack.com/query

License: MIT License

JavaScript 4.24% TypeScript 94.80% Svelte 0.80% Vue 0.08% HTML 0.08% CSS 0.01%
react hooks fetch cache async rest graphql data query stale

query's Introduction

TanStack Query Header

Hooks for fetching, caching and updating asynchronous data in React, Solid, Svelte and Vue

#TanStack semantic-release Join the discussion on Github Best of JS Gitpod Ready-to-Code

Enjoy this library? Try the entire TanStack! TanStack Table, TanStack Router, TanStack Virtual, React Charts, React Ranger

Visit tanstack.com/query for docs, guides, API and more!

Still on React Query v2? No problem! Check out the v2 docs here: https://github.com/TanStack/query/tree/2.x/docs/src/pages/docs.
Still on React Query v3? No problem! Check out the v3 docs here: https://tanstack.com/query/v3/docs/.
Still on React Query v4? No problem! Check out the v4 docs here: https://tanstack.com/query/v4/docs/.

Quick Features

  • Transport/protocol/backend agnostic data fetching (REST, GraphQL, promises, whatever!)
  • Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)
  • Parallel + Dependent Queries
  • Mutations + Reactive Query Refetching
  • Multi-layer Cache + Automatic Garbage Collection
  • Paginated + Cursor-based Queries
  • Load-More + Infinite Scroll Queries w/ Scroll Recovery
  • Request Cancellation
  • React Suspense + Fetch-As-You-Render Query Prefetching
  • Dedicated Devtools

query's People

Contributors

allcontributors[bot] avatar ardeora avatar arnaudbzn avatar arnoud-dv avatar balazsmatepetro avatar bennettdams avatar boschni avatar bviebahn avatar cherniavskii avatar coryhouse avatar damianosipiuk avatar dependabot[bot] avatar ephem avatar kamranayub avatar kentcdodds avatar lachlancollins avatar liaoliao666 avatar lukemorales avatar manudeli avatar michaeldeboey avatar mini-ghost avatar newbie012 avatar prateek3255 avatar raoufswe avatar size-plugin[bot] avatar tannerlinsley avatar tkdodo avatar wolverineks avatar zackderose avatar zorzysty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

query's Issues

How to mutate paginated cache for optimistic updates?

I have a list of data and I am transforming it into a normalized form (Object instead of an array) in my fetcher passed in useQuery and while applying optimistic updates, I just replace the mutated data with the new one using setQueryData.

But when the list is paginated, I cannot find a proper/recommended way to make it work. Now, since the cache stored is in an array, I'll have to go through each page and find the record and replace it.

Is there a way to make it simpler?
Thanks

Pull cached data?

Hey Tanner, thank you for another amazing library.

Is there a way to pull cached data to use in a component?

For example, I know "users" data is loaded when my App is started, and won't change.
So I know I can just pull the data from the cache when I need it.

Now I cache the data myself in context.

[Feature Request] useClearQueryCache Hook

Hey, I just thought it'd be nice to have a hook to clear the query cache.

I think it would just be:

const useClearQueryCache = () => {
  useEffect(() => {
    clearQueryCache()
  })
}

Reset mutation state

When a mutation raises and error, it would be nice if we could reset() the error state.

react-native support

now, in react-native throw error:
`
Unhandled JS Exception: TypeError: window.addEventListener is not a function. (In 'window.addEventListener('visibilitychange', revalidate, false)', 'window.addEventListener' is undefined)

RCTFatal
-[RCTExceptionsManager reportFatalException:stack:exceptionId:]
invoking_
-[NSInvocation invoke]
-[NSInvocation invokeWithTarget:]
-[RCTModuleMethod invokeWithBridge:module:arguments:]
facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&)
facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int)::$_0::operator()() const
invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int)
_dispatch_call_block_and_release
_dispatch_client_callout
_dispatch_lane_serial_drain
_dispatch_lane_invoke
_dispatch_workloop_worker_thread
_pthread_wqthread
start_wqthread
`

SSR?

Hi,

This package looks really great!
Does it support SSR (Server Side Rendering) like Apollo? Apollo is able to find all the requests in the view and fetch them server side.

Thank you for your work,
Lucas Willems

Allow option to transform the response body

In some case ,the API server will give a internal code in the response body like:

{
   code:"200",
   data:{},
   msg:"xxx"
}

It's helpful if we can transform the response body into somthing we want.

useQuery('key', queryFn , {
   transform:res=>{
       if(res.code==="200")return res.data       
   }
})

Performance issues?

Hi, we are midway through a project which uses react-query for all data-fetching activities. ATM all API calls are mocked using json files imported straight into the data layer of the app.

I started to look at the app's performance and saw a lot of initial CPU usage on the app's intial render, in which I think react-query is using a big part of it. For context, the initial render would be calling a number of times useQuery.

I ran the Chrome profiler and mostly what I see are a number of query.SetState & cleanup calls. I put a logpoint in the line for query.setState and it is being called 110 times, but in the Performance tab I only count 20 that are long enough (8-150 ms) to have a real impact.

Screen Shot 2019-12-13 at 11 16 07

Just in case, I ran the same performance audit using an incognito session with the production build and saw similar issues.

I was wondering if anyone has seen something similar and if you had any suggestions (useMemo?).
I'm not 100% sure I'm correctly looking at the data, and I'm happy to help clarify if not.

Thanks in advance!

refetchQueries doesn't work in mutation call

Based on the documentation, I expected passing the refetchQueries key in the second argument object to mutate would have refetched the specified queries.
e.g. mutate(newTodo, { refetchQueries: ["todos"]})

I am only able to get it to refetch when the key is passed in to the useMutation hook.
e.g. useMutation(addTodo, { refetchQueries: ["todos"]})

I've modified the EditTodo function in the default codesandbox app to recreate the issue.

Am I doing something wrong, is this a bug or does the documentation just need to be updated a bit to be consistent w/ the other examples?

Awesome library btw. Thanks!

suspense mode fetches twice when no prefetching

Hello,

I've been fighting a double fetch issue which I thought came from my custom hook that wraps useQuery. Turns out it seems to come from useQuery itself.

When using the suspense mode, the fetch function is called twice, once on initial render, and once when the data comes in. This only happens if the query was not prefetched. I've forked your codesandbox and disabled prefetching of projects when you click "Show projects", I've also added a log at the start of the fetch function so it's easy to debug in the console.

Have a look here: https://codesandbox.io/s/react-query-double-fetch-q5zgl

Let me know if there is additional details I can provide.

Thanks!

EDIT: note that I've noted tried the non-suspense mode. I'm assuming this is a suspense only issue.

Typescript support

First of all - thanks for great library. It simplified data fetching in my apps by order of magnitude.

The biggest feature I'm missing is Typescript support - to the point I have manually added TS definitions to most part of the API by hand. @tannerlinsley would you be interested in having them added to definitely-typed? AFAIK this is a recommended way of adding typings to projects that are not written in TS.

`query.error` is reset to null when using refetchInterval option

HI,
I've used react-query for polling request and noticed weird behavior.

Expect behavior:

When request fails, query.error shouldn't be reset null until request succeed.

Current behavior:

When request fails, query.error value is constantly switching between null and request error value

Steps to reproduce:

I will debug it and keep this issue updated if I'll get more info

Exception if variables are undefined

If there are no variables defined so it throws an exception.
In order to overcome this error i just pass "variables: {}" to all useQuery functions that i use

[Feature request] Testing Suite

Hey!
I really loved the package and it's API, and I think in order to make the contribution easier we should write up tests for the hooks and other functions.

How should we progress there? Maybe create an infrastructure to the testing and I will help writing some tests? I saw swr's tests and there is a lot in common and we can learn from their testing.

Thanks!

Fetch loop on repeated mounting and un-mounting

I've noticed a strange behaviour on repeated mounting and un-mounting.
What happens is that i have tabs component that mounts a specific components on every tab change,
so every time i switch between tabs, the current tab component is mounted again.
I'm using useQuery on each components to fetch the relevant information for the current tab.
When i'm doing the following actions the useQuery getting into fetch loop that never ends.

  1. mount the current tab component
  2. useQuery fetches the data
  3. move to other tab ( the previous component now unmounted and a new component tab mounted)
  4. get back to the first tab component ( now after the cacheTimeout has been expired )
  5. useQuery now getting into fetching loop with infinite fetch requests.

See the video below:
https://streamable.com/a90vs

Hope i'm clear enough, let me know if you need more information in order to reproduce it.

Thank you so much!

Add License?

Hi,
Thanks for your work, this API looks awesome!

I've noticed, that there's no License file added to this repo.
Would you mind adding one?

Comparison to zeit/swr

Could you help compare react-query and zeit/swr? Both project seem very similar, and the design decisions seem to overlap in many ways. It’s not obvious how to choose one over another. If you have any guidance, it would be very appreciated!

Why "isCached" always true ?

const { data, isCached} = useQuery('todos', fetchTodoList)
console.log(`isCached: `, isCached)

every time the component render, when data is not empty, it always isCached: true, even when network request. so, how to confirm the data is from net?

Add support for opening Next.js examples in Codesandbox

Installing node dependencies for any of the examples produces an error on a fresh clone of the repo, as react and react-dom are not included in package.json. Is this intended, or is it assumed these libraries would be installed globally? It's easy enough to get around it by adding them, but it might be more helpful if these were included by default in the dependency manifest.

Also, since all of the package.json files are the same, perhaps it might be easier to use one package.json for all examples and link them together via an index page that can be navigated in the browser? I was just wanting to check out the functionality of the library and it was a bit tedious to navigate and install deps in every directory. Happy to help with a PR, if it's a path you'd want to go down.

SSR: queries are cached on server

I've started to use react-query with next.js SSR using initialData option.
It works pretty good, but looks like queries are cached in server js bundle and are used across all requests.

Here's a minimal example reproducing the issue: https://codesandbox.io/s/react-query-ssr-cache-rkfsh

And a GIF which demonstrates the issue:
Screen Recording 2019-12-09 at 15 55 15

Note, that user index is incremented every time, but server always renders 1.
Here's what happens:

  • index is 1, there's no queries stored yet
  • user requests the page, data query is created and initialData is set
  • user refreshes the page
  • new initialData is passed to useQuery, but there already is a data query, so cached data is user on server render
  • page is rendered on client, since there's no queries in client bundle, new initialData is used

I've also checked if swr suffer from the same issue, but it works just fine - see https://codesandbox.io/s/swr-ssr-cache-qrmgn

Do you have any idea how it can be handled on react-query side?
As a workaround, I'm calling clearCachedQueries in _document.getInitialProps, which clears cached queries on server on every request

React Query Appreciation 🙂

Just wanted to leave a note here saying thanks and great work!
Very well-thought-out API, pleasure to use.

We are using the library in a closed source (sorry) project, so I'll sponsor while my client keeps paying!

Cheers!

Update without making network calls

Hello There
In the Todo App example, it is not possible neither to add a todo to the todo list nor updating an existing todo without making any additional network calls because updateQueries completely replaces old data.

        setState(old => ({
          ...old,
          [queryHash]: {
            ...old[queryHash],
            data,
          },
        }))

We may request a large amount of data (e.g. to display using a virtualized table) and we may also want the users to be able to edit records or add new ones; in this case, refetchQueries requires fetching a big amount of data just because of partial changes, (the server responds with updated record)
Have any plans on adding any features handling this process?
A temporary solution is to store fetched data in a React state and update it after mutations.

Integration with pagination on backend

Hi Tanner!

I've found that integration React Query with backend paginated APIs ("prev/next page", not load more/infinite scroll) is pretty difficult.

There's an example in readme, in which query variables are used for that:

function Todos() {
  const [page, setPage] = useState(0)

  const { data, isLoading, error } = useQuery(
    ['todos', { page }],
    fetchTodoList
  )

  const onNextPage = () => {
    setPage(page => page + 1)
  }

  return (
    <>
      {/* ... */}
      <button onClick={onNextPage}>Load next page</button>
    </>
  )
}

But i'm not sure, that this is the proper way to handle that.

Here are my doubts:

  • after changing the page - a new query is created, so data is null. This leads to blinking, since data from previous page aren't available yet, so UX experience is poor in this case
  • this pattern doesn't work with SSR. Consider this example:
import React from "react";
import fetch from "../lib/fetch";
import { useQuery } from "react-query";

function Component({ initialData }) {
  const [page, setPage] = React.useState(1);
  const { data } = useQuery(
    ["data", { page }],
    async () => await fetch(`/api/data?page=${page}`),
    { initialData }
  );
  // ...
}

Component.getInitialProps = async () => {
  const data = await fetch('/api/data?page=1');
  return { initialData: data };
};

When page changes, new query is created and it's data is set to initialData.
In this case user sees initialData before new query data is fetched:

Screen Recording 2019-12-11 at 15 57 44

Here's reproducible example: https://codesandbox.io/s/react-query-pagination-with-ssr-03tzu

Workaround

I've managed to workaround both issues by:

  • not using page as query variable
  • calling refetchQuery every time page changes
function Component({ initialData }) {
  const [page, setPage] = React.useState(1);
  const { data } = useQuery(
    "data",
    async () => await fetch(`/api/data?page=${page}`),
    { initialData }
  );

  React.useEffect(() => {
    refetchQuery('data');
  }, [page]);

  // ...
}

This did the trick, but:

  • it's not obvious
  • it doesn't feel right to me

Question

What is you experience in integration React Query with backend pagination and Is there idiomatic way to it?

Will be happy to discuss!

Prefetching on routing example

Hi!

I am amazed by the work that went into this and thankful for having a fetching / caching / suspense library that is independent of the fetching mechanism used. Thank you 🙇.

I know this is not really strictly react-query's land, but would you happen to have an example of prefetching on routing? Maybe with react-router or similar. I'm really tempted by your teasing of fetch-as-you-render which is also described in the react docs. I have read through this discussion in the react-router repo, but it's pretty hard getting a clear example / demo out of it 😬. So trying my luck in case anyone happen to have tried this already.

Cancel requests

There are often times in a web application where you need to send a request for the latest user interaction. We need a way to prevent subsequent (async) logic from running for all but the most recent request – something like Axios' cancel token or fetch()'s AbortController.

Add support for event handlers?

Would it be beneficial to add support for on fetch (or state change) event handlers since useEffect can be delayed or not run at all?

Example,

const info = useQuery('todos', fetchTodoList, { onError: (error) => showToast(error) });
const [mutate, { data, isLoading, error }] = useMutation(login, { onSuccess: (data) => reduxDispatch({type: 'LOAD_PROFILE', data: data }) });

On the last example, we can probably handle this in the event that made the call to mutate:

const data = await mutate({ title })
reduxDispatch({type: 'LOAD_PROFILE', payload: data });

¿Hook useIsFetching not Working?

I am trying to use this hook to show the buttons in loading mode, the problem is that what throws the hook is always false, and does not capture the first load and does not refetch them,
Are there any restrictions on this hook? o Should there be additional configuration?
Am I misunderstanding the meaning? o Do I have any erroneous configuration?
The isLoading does work correctly, but the global does not.
This is my _app with the provider.

// _app.tsx
 <StoreProvider store={store}>

                    <ThemeProvider theme={creatorCommerciTheme()}>

                        <CssBaseline/>

                        <ReactQueryConfigProvider>

                            <AppLayout type={AppRoles.Admin}>
                                <AnimatePresence exitBeforeEnter>


                                    <Component {...pageProps} key={router.route}/>

                                </AnimatePresence>

                            </AppLayout>
                        </ReactQueryConfigProvider>

                    </ThemeProvider>
</StoreProvider>

And this is one of my queries with a personalized hook.

// useCustomer.tsx
interface UseCustomerProps {
   id?: string | number;
}
export const useCustomerKey = 'UseCustomerGetCustomer';

function useCustomer(props: UseCustomerProps) {
   const customerApi = new CustomersAPI();
   return useQuery(
       [useCustomerKey, {id: props.id}],
       (args) => customerApi.getOneCustomer(args.id)
   );
}
// [cid].tsx
const CID = router.query.cid as string;
    const uiActions = useStoreActions((actions) => actions.ui);
    const ui = useStoreState((state) => state.ui);

   
    const {data: customer, isFetching, isLoading} = useCustomer({
        id: CID,
    });

Here I try to print the status of isFetching

// Form.tsx
const isFetching = useIsFetching();
const [mutate, { isLoading, error  }] = useUpdateCustomer();
console.log(isFetching); // ever false in loading o windows focus or mutation false false false false false

I need something more? Thank you very much c:
I use nextjs if they need extra information to replicate the problem can you tell me. I wanted to keep an eye on him but time consumes me so I will leave him here and I hope to be the only one that happens to him (hopefully it is my mistake)
LastVersion -- Jejejej

Manual query still fetches

Hi all,

Attempting to have a component which has a manual query. On initial page load it does not poll the server for the query.... however randomly, and I do not know why the query fetches, it seems to be on refocus? I have been unable to pinpoint the source of refetching.

Or is there a use case for manual querying that I could be missing.

I am passing the manual flag to be true

const myQuery = useQuery(
        ['myKey', { key }],
        performQuery,
        { manual: true, staleTime: HOUR_MS },
);

is the format I am using.

Custom cache key

Hey Tanner, thank you for another amazing library.

I would like to suggest to add custom cache key from useQuery, since the query be can changed depending on the implementation, it would be very helpful to be able to control the cache key name

discussion: custom hooks for graphql

Hi,

I've setup react-query for my fetching and caching recently. I really like it, it suppresses completely the need for a state store for parts of the app that are just read/write the API without much business logic. I now have a nice separation of where data lies depending on whether I'm just read-writing it, or manipulating it in complex ways. Particularly love the refetch on mutation pattern. And sending some love for the suspense mode of course. Thanks for the great lib!

Now, to the topic I wanted to discuss. My API is using GraphQL and I have created a custom hook that wraps react-query to incorporate all the repetitive code I would do in each component.

I don't have any burning question, just wanted to share, get some feedback, have some conversation about this approach. I hope it can help me and others. Maybe there are things in here that can be generalized and reused whether in react-query or another small wrapper lib.

Oh, and please let me know if there is a better place to discuss this!

Below is my implementation.

// gql.js - my custom hook
import { useEffect } from 'react'
import { useQuery, useMutation } from 'react-query'
import { GraphQLClient } from 'graphql-request'
import { print } from 'graphql/language/printer'

import { useAuth0 } from '../contexts/Auth0'

const getClient = token =>
  new GraphQLClient(process.env.REACT_APP_GQL_ENDPOINT, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  })

export const getQueryKey = query => query.definitions[0].name.value

// qvFn stands for query & variables function
export const useGqlQuery = qvFn => {
  const { getTokenSilently } = useAuth0()
  return useQuery(
    () => {
      const [query, variables] = qvFn()
      return [getQueryKey(query), variables]
    },
    async variables => {
      const token = await getTokenSilently()
      return getClient(token).request(print(qvFn()[0]), variables)
    }
  )
}

export const useGqlMutation = (query, options = {}) => {
  const { getTokenSilently } = useAuth0()
  const [mutate, { data, isLoading, error }] = useMutation(
    async variables => {
      const token = await getTokenSilently()
      return getClient(token).request(print(query), variables)
    },
    {
      refetchQueries: (options.refetchQueries || []).map(getQueryKey),
      refetchQueriesOnFailure: (options.refetchQueriesOnFailure || []).map(getQueryKey)
    }
  )
  const callOnData = () => {
    if (data && options.onData) {
      options.onData(data)
    }
  }
  useEffect(callOnData, [data])
  const callOnError = () => {
    if (error && options.onError) {
      options.onError(error)
    }
  }
  useEffect(callOnError, [error])
  return [mutate, { data, isLoading, error }]
}

and the querying component looks like this:

// component.js - a random component
// imports [...]
import gql from 'graphql-tag'

import { useGqlQuery, useGqlMutation } from '../hooks/gql'

export const fetchData = gql`[...]`
const updateData = gql`[...]`

const MyComponent = () => {
  const { data, isFetching } = useGqlQuery(() => [fetchData, { /* vars [...] */ }])
  const [mutate, { isLoading }] = useGqlMutation(updateData, {
    refetchQueries: [fetchData],
    onData: () => setSuccess('<success message>'), // set some state
    onError: () => setError('<error message>') // set some state
  })
  // [...] state / event handlers / render method
}

export default MyComponent

Note: I'm only using the suspense mode.

What does this adds to the normal hooks:

  • custom fetch method based on graphql-request
  • graphql queries are passed in AST format
  • queries are "printed" just to fetch (because graphql-request do not consume gql AST objects)
  • gql is used to generate the AST (and enables linting with the good editor extensions)
  • generate unique key based on query AST
  • unique key is also generated from the same query object when prefetching or refetching
  • i'm keeping the query function and throw behaviour (I love it)
  • auth token is injected
  • mutations have onData and onError options that are functions I can run when the query resolves or fails, this saves on a bunch of useEffect calls in the component.

I like graphql-request because it's minimal, instead of going with something like apollo-client, we can separate concerns of fetching with a dedicated tiny lib (graphql-request), and caching + suspense with another tiny lib (react-query).

Some of these would be feasible with just a custom fetch method. Not key generation, and it seems nice to just pass a query AST and have the key be deterministic. Like this, it's impossible to end up with non-matching keys. What do you think of this? I could also hash the whole query body instead of just take the name, it would be more safe. It's probably something @tannerlinsley has thought about in choosing string keys instead of hashing queries.

Also onData and onError are probably hard to accomplish without a custom hook wrapper, and I feel it's extra nice. Maybe something worth adding to the lib?

Are there any pitfalls I have missed here? Or anything nifty I could add? Do you think that's a good approach? I'm curious what the community will think about this.

Error is not getting cought when coming back to the window

Hey, great library!
I noticed that when I useQuery and it fails, go out of the page and then go back - the error will not be caught in useQuery but be raised to the UI.

How to test?

  1. Use useQuery to a endpoint that does not work (using async await)
  2. Let it fail one time, go out of the tab and go back in.
  3. You should see the Ui crashes.

Thanks!

Request to add isCached to onSucces

Hi,
I would like to have isCached info in the onSuccess. The use case is using AsyncTypeahead and to ease the processing of new data - if I know that it comes from cache I would know that I have this data already locally and would not need to compare for uniqiness like bellow:

const { isLoading } = useQuery(['selectPublisher', { query }], fetchPublishers, {
		onSuccess: data => {
			publishersResults = _uniqBy([...publishersResults, ...data], ({ id }) => id)
		},
	})

I find onSuccess is very usefull for postprocessing. Maybe it is usefull to add also other useQuery return values to onSucess params.

ReferenceError: regeneratorRuntime is not defined

When running this I'm hitting the error ReferenceError: regeneratorRuntime is not defined. I think this has to do with how the library is being built. You can work around this by configuring babel but that seems like a lot of overhead for consumers.

initialData option for useQuery

Is it possible to have an initialData option for useQuery like in swr.

I'm using Next.js to fetch data in getInitialProps and i'd like that value to be the initial data when the same request is made with useQuery.

API for clearing cache

The problem

There's a scenario, which is pretty common:

  • user logs in
  • some user data is fetched
  • user logs out
  • different user logs in and for a moment sees previous user's data

Normally, all user data should be deleted after log out, but there's no API for that at the moment.

I've tried setQueryData function to clear some queries, but it didn't work for me, since it doesn't make those query stale.

I've managed to clear cache like this:

import { queries } from 'react-query';

function handleLogout() {
    queries.length = 0;
}

But I'm not sure if it is safe to do this, since this is not a public API.

Proposed solution

Introduce clearQueries function, which will:

  • clear all queries if called without arguments
  • clear all queries except those provided as first argument.

The second option may be useful for applications, which are partly public. This will allow to clear user data cache, but keep public data cache.

Let me know do you think about that

useFunctionQuery from documentation cause infinite loop

I liked the idea for key to use a function itself used for fetching the data because of no need to use strings or additional constants. Tried to use it from documentation and it triggers infinite rapid fetching. A function reference is stable (exported from separate module) so something inside custom hook needs to be memoized? Any guidance how to solve this?

I'm talking about this custom hook:

function useQuery(functionTuple, options) { const [queryFn] = Array.isArray(functionTuple) ? functionTuple : [functionTuple]; return useReactQuery(functionTuple, queryFn, options); }

no refetch with suspense since 0.3.17

I've updated my dependencies and the fetching behaviour is different. In my app, whenever I now navigate to a page I was previously at, there is no refetch if I use suspense.

The same happens in the suspense codesandbox examples, please notice the network requests as I click the button:

0.3.21 without suspense:
0321-no-suspense

0.3.21 with suspense:
0321-suspense

0.3.16 with suspense:
0316-suspense

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.