I
I
Ilya2020-10-21 18:21:18
React
Ilya, 2020-10-21 18:21:18

How to organize the fetch function as a module?

Hello everyone, I started to learn React, I work with api.
Using the fetch function, I pull out json from the API, I will often access the API for different pieces of code, so fetch needs to be moved to a separate module and connected if necessary. After vygreb json, I change the state of the component, they say everything has loaded, there are no errors. And how can I make a separate full-fledged module out of this? What parameters, url, and callbacks should there be for changing states? Tell me, and then experience in this matter is not enough. What would be the best way to do it? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hellcaster, 2020-10-21
@web_Developer_Victor

I use this (it's a hook, but it might help):

spoiler

import {useState, useCallback} from 'react';

export default () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const request = useCallback(async (url, method = `GET`, body = null, headers = {}) => {
    setLoading(true);

    try {
      if (body) {
        body = JSON.stringify(body);
        headers[`Content-Type`] = `application/json`;
      }

      const response = await fetch(url, { method, body, headers });
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Something went wrong');
      }

      setLoading(false);

      return data;
    } catch (e) {
      setLoading(false);
      setError(e.message);
      throw e;
    }
  }, []);

  const clearError = useCallback(() => setError(null), []);

  return {loading, request, error, clearError}
}

Use like this:
const {loading, request, error, clearError} = useHttp();

const handler = async () => {
  const response = await request(`/api/auth/login`, `POST`, {...form}); // можно четвертым передать headers
 }

if (loading) {} // если грузятся данние
if (error) {} // если прозойшла ошибка

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question