React query fetch data like a pro with react

React Query is a JavaScript library that simplifies state management and data fetching in React applications. It provides an intuitive API for handling asynchronous operations, caching data, and optimizing network requests. With React Query, you can streamline your development process and create efficient React applications.

1. How do we fetch data without react query

  • First, create a state to save the data from the api
  • Next, create a function to fetch data the data then update the created state with the value returned from api
  • Finnally, use useEffect to call this function when component first mount
const User = () => {
  const [usersData, setUsersData] = useState()
  
  const fetchUsers = async () => {
    const res = await fetch("/uses")
    const data = await res.json()
    setUsersData(data)
  }
  
  useEffect(() => {
    fetchUsers()
  }, [])
  
  return (
    //do something with usersData state here
  
  )

}
  • For a simple demo or simple task you can do it but things get more complex when you need to error handling, check loading status, refetch the data, catching data, retry when error, apply some logic about pagination or search filter via query params or maybe infinity scroll

2. Ok let’s see how React Query help us

  • First, setup react query
yarn add react-query
  • Setup query client in project
import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
const queryClient = new QueryClient()

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <User />
    </QueryClientProvider>
  )
}
  • Now every component that beneath the QueryClientProvider can use the power of the react query
  • How ?
const User = () => {  
  const fetchUsers = async () => {
    const res = await fetch("/uses")
    const data = await res.json()
    return data
  }
  
  const {data, isFetching, error} = useQuery("users", () => fetchUsers())
  
  return (
    //do something with data
  
  )

}
  • The code from section 1 will be shorten like this, useQuery is a hook from react-query that takes 3 params: first is queryKey, second is queryFunction the third params is optional is is the query options
  • How it actually works ? each query have a query key this help react query manage all query that you’ve created in your app, react query will try to call queryFunction that you pass it (second params in useQuery hook) if this function success react query update the data variable that we destructuring, if the queryFunction throw errors it will retry 3 times if error still occurs the error variable will be updated. Last the isFetching variable is a boolean indicate that the query is running or not.
  • A lot of thing have done in just one line of code right ?
  • Let’s take a more realistic example when you need fetch data paginate it and implement some search functions.
const User = () => {  
  const [dataSearch, setDataSearch] = useState({
    page: 1,
    limit: 10,
    q: "" //for search
  })
  const fetchUsers = async (params={}) => {
    const paramsString = queryString.stringify(params) //?page=1&limit=100&q=
    const res = await fetch("/uses" + paramsString)
    const data = await res.json()
    return data
  }
  //upadate the data search when page or limit change or user enter the search box
  
  const {data, isFetching, error} = useQuery(["users", dataSearch], ({queryKey}) => fetchUsers(queryKey[1]))
  
  return (
    //do something with data
  
  )

}
  • We just focus on how we use react-query so i dont show how we setup search box or pagination (this will depend on your backend api )
  • So, let break down the example code: first we create a state for the params which will be stringify to query string use query-string lib. you can install it: https://www.npmjs.com/package/query-string
  • We update the fetchUsers() function so it accept one parametter is the params that we need to send to the api
  • in useQuery hook. The queryKey that i mentioned above it can be an array and we can get the queryKey in the query function by destructuring it in queryFunction params ({queryKey}) => {} so the queryKey[1] is the dataSearch state that we passed in.
  • Why we need to like this cause when we update the dataSearch => it take the queryKey changes queryKey changes then react query will re-run the queryfunction so we have new data each time we change the search params. Make sens right ?

3. Conclusion

Now, you know how to use react-query, just the basics visit: https://tanstack.com/query/v3/docs/react/overview offficial docs for more information. Ex implement infinite query with useInfiniteQuery() hooks or update data with useMutation(),…. In this blog, i just focus on how we fetch data using react-quey

4. Referrences

__CodingCat__

Leave a Reply

Your email address will not be published. Required fields are marked *