TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte

Let’s learn react query V4.

React Query is often described as the missing data-fetching library for React. Still, in more technical terms, it makes fetching, caching, synchronizing, and updating server state in your React applications a bree…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Rajiv Chaulagain

Let's learn react query V4.

React Query is often described as the missing data-fetching library for React. Still, in more technical terms, it makes fetching, caching, synchronizing, and updating server state in your React applications a breeze.

Why react query ?

-> React query as often said is used for state management of server data and using react query the we should write less code so it is also an alternate of redux toolkit.

Starting with react-query we need to provide a context provider given by react-query and then we can use the hook provided by react-query , Let's look onto and example.

In app.js file configure by following ways,

import {
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query'

// Create a client
const queryClient = new QueryClient()

export function App() {
  return (
    // Provide the client to your App
    <QueryClientProvider client={queryClient}>
    //out app goes here......
    </QueryClientProvider>
  )
}

Now inside our component we can access the data.

So for fetching data in component Products.js ,

import {
  useQuery,
} from '@tanstack/react-query'
import { getProducts } from '../my-api'

function Products() {

  // Queries
  const {data , isLoading , isError} = useQuery(['products'], getProducts)
if(isLoading) return "Loading ..."
if(isError) return "Error ..."

//then we can assume the data is success

  return (
    <div>
      <ul>
        {data?.map(product => (
          <li key={product.id}>{product.title}</li>
        ))}
      </ul>
    </div>
  )
}

Here , we provided and unique key as "products" inside useQuery hook that provides the caching and it should be unique.

The getProducts function is a promise based function that returns data if success and throws error if any error

Here we used the hook called useQuery from react-query that provides following things.

  1. data -> It gives the data from server eg : data : [{title : 'title'}]
  2. isLoading -> It provides the loading state as boolean and till our data is being fetched and currently in loading state.
  3. isError -> if there is any problem while fetching data the error will be provided on error state. some more ways are :-
  4. error -> It provides the error message .
  5. isFetching -> after every render react-query fetches and isFetching will be true while isLoading is only true during initial render.

Now for posting data we use Next hook as useMutation .

so In AddProduct Component ,


import {
  useQuery,
  useMutation,
  useQueryClient,
} from '@tanstack/react-query';

const AddProducts = () => {
const [data , setData] = useState('');
 // Access the client
  const queryClient = useQueryClient();

const mutation = useMutation(mutationFn , {
onSuccess : () => {
   // Invalidate and refetch
      queryClient.invalidateQueries(['products'])}
}
)

return (
<>
  <input value={data} setData={(e) => setData(e.target.value)} />
<button onClick={mutation.mutate(data)}>Submit</button> 
</>
)
}

Here, useMutation hooks take mutation function.
here mutate is the callback function that takes the data and provides in useMutation hook.
and invalidate query will refetch the data or products.

Conclusion,

React query is the most powerful library for server side state management and the enabled property of react query is the quiet impressive.
example,

const params = useParams();
const id = Number(params?.id)
const {data} = useQuery([''] , queryFn , {
enabled : !!id
})

so , if id is true then only this query will fetch the data else the query is disabled.


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Rajiv Chaulagain


Print Share Comment Cite Upload Translate Updates
APA

Rajiv Chaulagain | Sciencx (2022-10-14T15:15:31+00:00) TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte. Retrieved from https://www.scien.cx/2022/10/14/tanstack-query-v4-powerful-asynchronous-state-management-for-ts-js-react-solid-vue-and-svelte/

MLA
" » TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte." Rajiv Chaulagain | Sciencx - Friday October 14, 2022, https://www.scien.cx/2022/10/14/tanstack-query-v4-powerful-asynchronous-state-management-for-ts-js-react-solid-vue-and-svelte/
HARVARD
Rajiv Chaulagain | Sciencx Friday October 14, 2022 » TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte., viewed ,<https://www.scien.cx/2022/10/14/tanstack-query-v4-powerful-asynchronous-state-management-for-ts-js-react-solid-vue-and-svelte/>
VANCOUVER
Rajiv Chaulagain | Sciencx - » TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/14/tanstack-query-v4-powerful-asynchronous-state-management-for-ts-js-react-solid-vue-and-svelte/
CHICAGO
" » TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte." Rajiv Chaulagain | Sciencx - Accessed . https://www.scien.cx/2022/10/14/tanstack-query-v4-powerful-asynchronous-state-management-for-ts-js-react-solid-vue-and-svelte/
IEEE
" » TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte." Rajiv Chaulagain | Sciencx [Online]. Available: https://www.scien.cx/2022/10/14/tanstack-query-v4-powerful-asynchronous-state-management-for-ts-js-react-solid-vue-and-svelte/. [Accessed: ]
rf:citation
» TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte | Rajiv Chaulagain | Sciencx | https://www.scien.cx/2022/10/14/tanstack-query-v4-powerful-asynchronous-state-management-for-ts-js-react-solid-vue-and-svelte/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.