hooks for handling fetch data and use react query

rezaabaskhanian

RezaAbaskhanian

Posted on April 23, 2023

hooks for handling fetch data and use react query

In this example, we've imported the useFetchData hook and called it with the API endpoint URL. The useFetchData hook returns the same object that the useQuery hook returns, so we can use the same conditional rendering logic to handle loading and error states.

Using custom hooks like this can make your code more modular and reusable, and it can also make it easier to switch between different data fetching libraries (such as switching from React Query to another library) in the future if necessary.

import { useQuery } from 'react-query';

function useFetchData(url) {
  return useQuery(['data', url], async () => {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  });
}

export default useFetchData;
Enter fullscreen mode Exit fullscreen mode
import React from 'react';
import { View, Text } from 'react-native';
import useFetchData from './useFetchData';

function MyComponent() {
  const { isLoading, isError, data, error } = useFetchData('https://api.example.com/data');

  if (isLoading) {
    return <Text>Loading...</Text>;
  }

  if (isError) {
    return <Text>Error: {error.message}</Text>;
  }

  return (
    <View>
      {data.map(item => (
        <Text key={item.id}>{item.name}</Text>
      ))}
    </View>
  );
}

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
rezaabaskhanian
RezaAbaskhanian

Posted on April 23, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Angular Form Array
angular Angular Form Array

November 29, 2024

Week 13: Release 0.4: Planning
undefined Week 13: Release 0.4: Planning

November 29, 2024

Can a Solo Developer Build a SaaS App?
undefined Can a Solo Developer Build a SaaS App?

November 29, 2024