DEV Community

Francisldn
Francisldn

Posted on

 

React Data Fetching Pattern - Part V

This article is a continuation of:

Click here to access the Github repo for the code examples discussed below.

React Query

An alternative React data fetching library that provides similar utilities as SWR is React Query.

React Query provides a hook called useQuery which accepts a query key and a callback function (fetcher). Similar to SWR, it also allows for integration with React Suspense API by simply including the option suspense: true. If the fetcher callback requires a parameter (eg: URL), we can include this as a 2nd item in the array after the query key. useQuery will return data, isLoading, error, isError to be accessed by React components.

To allow for code reusability and avoid prop-drilling, we can create a custom hook to perform the logic of data fetching using React Query, as below.

const fetcher = async(apiURL:string) => {
    try {
      const {results: data} = await getUsers(apiURL)
      return data.map((user:UserApi) => ({
          id: user.id.value,
          firstName: user.name.first,
          lastName: user.name.last,
          username: user.login.username,
          email: user.email,  
      }))
    } catch(error) {
      throw new Error('unable to fetch data')
    }
}

const useUsers = () => {
    const {isLoading, isError, data, error} = useQuery(['users',apiURL], () => fetcher(apiURL),{suspense: true})

    return ({
        users: data,
        isLoading,
        isError,
        error
    })
}

export default useUsers;

Enter fullscreen mode Exit fullscreen mode

Before we can access the data in any React component, we have to wrap the QueryClientProvider around the top-level component (<App />).

import { QueryClientProvider, QueryClient } from 'react-query';

const queryClient = new QueryClient()

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
);

Enter fullscreen mode Exit fullscreen mode

Within React component, we can now access the users state from useUsers hook, as below.

export default function CardList() {
  const {users} = useUsers()

  return (
    <div className="grid sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 justify-center grid-cols-1 mt-8">
      <Suspense fallback={<Loading />}>
        {
          users.map((user:User) => (<CardItem key={user.id} user={user}/>))
        }
      </Suspense>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Pros

  • Similar to SWR, the initial code set-up is relatively easy and it is also performant.

For more information on React Query, see here.

I hope these article provides valuable information to you as a React developer.

If you like the content, please hit the like button so that it can reach more people.

Top comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React