Mastering data fetching with React Query and React js
Tags: react, javascript, webdev
Published: 2022-10-14 15:15:31

## 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.