How can I simplify HTTP requests in React?

Asked

Viewed 46 times

0

I am currently working on a project that has modules with multiple API requests. Similarly, cases of "ordered" requests are frequent, that is, they are carried out as long as a given condition is met. In this way, in the course of the work I could notice that the requests were leaving the code excessively verbose, this because a single request demands a considerable block of code.

Example of the format I’m currently using:

useEffect(() => {
    const cancelToken = axios.CancelToken.source();
    api
      .get(getUfs(), {
        cancelToken: cancelToken.token
      })
      .then((res) => {
        if (res.status === 200) {
          const options = createOptions(res.data, {
            label: "sigla",
            value: "sigla"
          });
          selectUfs.setOptions(options);
        }
      })
      .catch((error) => null);
    return () => cancelToken.cancel();
  }, []);

Considering only one request in the component this model did not bring any problems, however, as the number of requests increases the readability of the code is impaired. In my search for solutions I found few alternatives, some excessively complex, others that only work in a certain situation, however, the one that seemed more attractive was the creation of a hook customized to handle requests. In general, I aim to decrease the amount of code while preserving the functionality. If anyone knows a more efficient way to deal with requests and want to share, I thank you from now on :)

  • Young man, just ask me a question of these modernities, does this code run on the server or is it running on the front? But answering your question, this seems to be a form of Callback Hell, I think what solves this are Javascript files or something similar, like Fluent interface, search as to what they should meet.

  • Hello, first I’d like to thank you for your answer. Well, this code is running on the front and at the moment I’m not having any problems related to Callback Hell... In this case I’m just trying to find a more simplified way to make the requests in order to make the code less verbose and improve readability.

  • People call it Callback Hell in Javascript when the callbacks nest and the code gets bad to follow in a similar way as the readability of yours. I don’t know if this is your case, but it sounds like it. As for running on the front end, I do not know if it is the most appropriate, I think that a sequence of HTTP calls so medium with transactional behavior should run on the server. If it were a mobile app for example the most unstable mobile network could harm. But I don’t know. People always talk so good about React, it must be a valid way of doing.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.