React fetch() POST

Asked

Viewed 1,589 times

2

I have a API (POST) in which I pass some parameter and it returns me results and the question is the following:

I got a guy Dashboard where I have to take DIA data and MES data (using the same API, but passing different parameters.

To get the data of the day I use:

import React, {Component} from 'react'
import '../../index.css';

export default class FaturamentoDia extends Component{

    constructor(props) {
      super(props);
      this.state = {
        itensDia: [],
        wTotGeral: '',
      };
    }


    componentDidMount() {

      const data = {
        "aEmp" : ["004"],
        "PeriodoDe" : "2019-1-15T12:54:21Z",
        "PeriodoAte" : "2019-1-15T12:54:21Z"
      }
      const requestInfoDia = {
          method: 'POST',
          body: JSON.stringify(data),
          headers: new Headers({
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          }),
      };

        const dadosDia = fetch('http://10.0.0.49:9000/rzcFatPeriodo', requestInfoDia); 
        dadosDia.then(response => { 
          console.log(response);
          return response.json(); 

        }).then(itensDia => {

        var swTotGeral = 0;         

        for (var i=0;i<itensDia.length;i++){
          if(itensDia[i].DEFFATURAMENTO === 'D'){
            var wValAux = -1;
          }else{
            wValAux = 1;
          }
          if(itensDia[i].ESTADONF !== 'C' && itensDia[i].ESTADONF !== 'I' && itensDia[i].ESTADONF !== 'D' ){
            swTotGeral = swTotGeral + (itensDia[i].VALCONTABIL* wValAux);

          }


        }


        var wTotGeral = swTotGeral.toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});

        console.log("Dia: "+wTotGeral)       

          this.setState({ itensDia, wTotGeral })

        });
   } 
   render() {
     const {wTotGeral} = this.state

     return (

      <div>
        {wTotGeral}
      </div> 

    );  
   }

}

The final result appears correctly in wTotGeral;

in another file I do the month .... changing only

const data = {
"aEmp" : ["004"],
"PeriodoDe" : "2019-1-01T12:54:21Z",
"PeriodoAte" : "2019-1-31T12:54:21Z"

}

that is taking data of the whole month, the problem that when I will show the data on the screen, a request returns 200 (ok) and shows the data and the other returns 500.

inserir a descrição da imagem aqui

Could someone give me a hand on how to make the data appear at the same time and I tried await before the fetch, but it didn’t work out.

1 answer

3


You cannot be assured that both requests will be resolved at the same time as they are in different components - unless they are executed in parallel through a saga, for example.

But you can ensure that both sections will plot the data at the same time by reviewing the architecture of your application and taking both requests to a higher-order component that would be responsible for distributing the data after getting answers. The plotting of the data can be blocked by a loading state, which ensures that the data will only be displayed after the resolution of the requests.

Since your requests are identical, having only the payload changed, you could implement a service that takes responsibility for receiving the request data and performing it, something like that:

async function getBilling(requestData) {
  const requestOptions = {
    method: 'POST',
    body: JSON.stringify(requestData),
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
  };

  const response = await fetch('http://10.0.0.49:9000/rzcFatPeriodo', requestOptions);

  return response?.json();
}

This would reduce repeated code and facilitate maintenance. In its major order component (that would be responsible for rendering the sections you need that have data displayed at the same time), would look something like:

componentDidMount() {
  ...

  this.setState(prevState => ({ ...prevState, isLoading: true }));

  const billingOfDayRequestData = {
    aEmp: ['004'],
    PeriodoDe: '2019-1-15T12:54:21Z',
    PeriodoAte: '2019-1-15T12:54:21Z',
  }

  const billingOfDay = await getBilling(billingOfDayRequestData);

  const billingOfMonthRequestData = {
    aEmp: ['004'],
    PeriodoDe: '2019-1-01T12:54:21Z',
    PeriodoAte: '2019-1-31T12:54:21Z',
  }

  const billingOfMonth = await getBilling(billingOfDayRequestData);

  this.setState(prevState => ({ ...prevState, billingOfDay, billingOfMonth, isLoading: false  }));

  ...
}

If using prevState raises questions, you can get a good answer at: https://stackoverflow.com/a/54807520/11009883

I hope I’ve helped.

  • It sure helped a lot... I’ll try to work on that tip of yours.... but it left me a doubt ... in this way how I would search the data of my API ? (I am beginner in this area)

  • @Alexandreprezzi The service is assuming the responsibility of carrying out the requisition, as long as it receives the data, serving as an abstraction so that it can be used by one or more components, as happens in const billingOfDay = await getBilling(billingOfDayRequestData);.Services are usually defined in a separate directory in the project, often in /src/services.

Browser other questions tagged

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