DEV Community

Cover image for What is react-query ? A CURD operation using react-query
KaRthick
KaRthick

Posted on

What is react-query ? A CURD operation using react-query

What is react-query ?

react-query is a hooks for fetching, caching and updating asynchronous data in react.

What is solves ?

react-query makes things easier that we're facing while fetching the data from the server.It can handle REST,graphQL or any sort of API request.

--> Auto-Caching : If a API end point is initiated for the first time react-query will cache the request so when you initiate the same API now the API will be blinking fast .

--> Windows Refocusing: Whenever the new focus is made to the application window the api will be called to ensure the data is up to date!.
But wait each time making a API request will it takes delay ??? answer is strictly no the second time it's loaded using the cache

seems cool??? it has many more cool stuff's

Alt Text

*image taken from official docs

useQuery

The major term to be known before using the react-query is useQuery. It is the hook which is used to make an API request .
const { status, data, error } = useQuery('todos', fetchTodoList)
this is the way to use useQuery

'todos' : the unique identifier(queryKey) for the query it's the thing used to differentiate between multiple quries,used to update things in the query.
fetchTodoList : it is the function where the API call can be done .
const fetchTodoList=()=>return new Promise(//_fetch/axios call here_)
status : it holds the status of API (success,loading)
data : the data that API returns
error: returns if any error occurs in the API

queryCache

Majority of the operations of the performed in react-query is done using queryCache.

useMutation

useMutation is used to perform the operations in the server like add,edit,delete

The major one's that we're going to cover in queryCache are,
-->setQueryData : used to set the value in the query based on queryKey
-->refetchQueries : used to refetch the particular query
-->removeQueries : used to remove the query from cache

we'll see the practical use of each in the following example

Display List

the following is a thing to display the list item
* uses jsonplaceholder api

!!Note : I recommend to open the codesandebox in a new window and check the network tab to see the API call's

Alt Text

this is the custom hooks to fetch the list data .
!!Note: Use custom hooks to reuse the query anywhere you need

const { status, data,error } = useListDataFetch();
this custom hooks has the details returned by the api in data. If you check the network tab you can see the fetch happing on every time a new focus is set to the application .

Edit List

Edit functionality has some more things to see
Alt Text

onMutate : it is the things that executes before the API call success.
Specially for reactivity kind of things.
onError : executes if any error occurs in the API.
onSettled/onSuccess : executes after the API call is success.

queryCache.getQueryData('listData') : gets the values from the querykey listData.

queryCache.setQueryData('listData', updatedValue) : sets the value in the udpated value in the querykey listData.

queryCache.refetchQueries('listData') : it's used to refetch the query to ensure UI has updated data . Usually better to use after edit/add/delete

!!Note : Edited things will be restored after the API call success because it's just a fake API to show you how things actually works

Delete List

Delete is similar to the edit with only one minimal change

Alt Text

Hope you got a some things know about react-query . It's such a nice and useful package to use with zero dependencies . Definitely you can try react-query in your appplication

You can get the code also here

Check out the official docs they have a amazing and clear docs link

A video tutorial link

Thanks for your time !!
See you all then
Happy Coding stay safe!

Top comments (2)

Collapse
 
brandiqa profile image
Michael Wanyoike

Great article. I am using React Query 3, for the Delete mutation, I implemented it this way:

import axios from 'axios'
import { useMutation, useQueryClient } from 'react-query'

function App() {
  const deleteMutation = useMutation(
    (id) => axios.delete(`http://localhost:3004/users/${id}`),
    {
      onSuccess: () => {
        queryClient.invalidateQueries()
      },
    }
  )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
karthick30 profile image
KaRthick

LG! yeah react query updated a lot !