DEV Community

RezaAbaskhanian
RezaAbaskhanian

Posted on

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

Top comments (1)

Collapse
 
pcelac profile image
Aleks

Please delete this "tutorial".