Создание пользовательских хуков для получения данных в React

Я могу предоставить вам несколько методов создания собственного перехватчика для получения данных в React. Вот несколько примеров:

  1. Использование хуков useStateи useEffect:

    import { useState, useEffect } from 'react';
    function useDataFetcher(url) {
    const [data, setData] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const response = await fetch(url);
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        setError(error);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
    }, [url]);
    return { data, isLoading, error };
    }
    // Usage
    function MyComponent() {
    const { data, isLoading, error } = useDataFetcher('https://api.example.com/data');
    if (isLoading) {
    return <div>Loading...</div>;
    }
    if (error) {
    return <div>Error: {error.message}</div>;
    }
    return (
    <div>
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
    );
    }
  2. Использование хука useReducer:

    import { useReducer, useEffect } from 'react';
    const dataFetchReducer = (state, action) => {
    switch (action.type) {
    case 'FETCH_INIT':
      return { ...state, isLoading: true, error: null };
    case 'FETCH_SUCCESS':
      return { ...state, isLoading: false, data: action.payload };
    case 'FETCH_FAILURE':
      return { ...state, isLoading: false, error: action.payload };
    default:
      throw new Error('Unhandled action type');
    }
    };
    function useDataFetcher(url) {
    const [state, dispatch] = useReducer(dataFetchReducer, {
    isLoading: false,
    data: null,
    error: null
    });
    useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_INIT' });
      try {
        const response = await fetch(url);
        const jsonData = await response.json();
        dispatch({ type: 'FETCH_SUCCESS', payload: jsonData });
      } catch (error) {
        dispatch({ type: 'FETCH_FAILURE', payload: error });
      }
    };
    fetchData();
    }, [url]);
    return state;
    }
    // Usage
    function MyComponent() {
    const { data, isLoading, error } = useDataFetcher('https://api.example.com/data');
    if (isLoading) {
    return <div>Loading...</div>;
    }
    if (error) {
    return <div>Error: {error.message}</div>;
    }
    return (
    <div>
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
    );
    }

Это всего лишь два примера того, как можно создавать собственные перехватчики для получения данных в React. Существуют и другие варианты и шаблоны, которые вы можете изучить в зависимости от ваших конкретных требований.