Dynamic consumption of REST React API

Asked

Viewed 92 times

-1

I am new in the area and know how I can do to have a dynamic consumption of the Rest api in React. Currently my query is fixed and my idea would be to take the value that the user type for query, how can I pass this information via parameter?

import axios from 'axios';

const api = axios.create({
    baseURL: 'https://localhost:44340/api'
});

export default api;

My component

import React, { Component } from 'react';
import api from '../../../SolicitacaoApi';
import './style.css'

class SolicitacaoTable extends Component {
  state = {
    solicitacao: [],
  }
  async componentDidMount() {
    const response = await api.get('solicitacao?protocolo='+1000250170);        
    this.setState({ solicitacao: response.data });    
  }
  render() {
    const { solicitacao } = this.state;         
    return (            
      <div>
        <div className="main-table">                
            <table className="table-wrapper">
            <thead>
                <tr>
                    <th>Protocolo</th>
                    <th>Titular</th>
                    <th>Email</th>
                    <th>Data de inclusão</th>
                    <th>Telefone</th>
                    <th>Tipo de produto</th>
                    <th>Tipo de emissão</th>
                    <th className="column-status">Status</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>{solicitacao.protocolo}</td>
                    <td>{solicitacao.titularNome}</td>                                         
                    <td>{solicitacao.email}</td>      
                    <td>{solicitacao.dtInclusao}</td>                       
                    <td>{solicitacao.telefone}</td>
                    <td>{solicitacao.tipoProduto}</td>
                    <td>{solicitacao.tipoEmissao}</td>              
                    <td>
                        <div className={'status status-'+solicitacao.idStatusSolicitacao}>
                            {solicitacao.statusSolicitacao}
                        </div>
                </td>
            </tr>            
          </tbody>
        </table>
        </div>          
      </div>
    );
  };
};
export default SolicitacaoTable;
  • The question is unclear, where does the value come from? What exactly is the problem? You can use the componentDidUpdate to observe changes in the state or props and perform the request when desired, since the componentDidMount will only be executed once

2 answers

0

You can create a useEffect for the variable you want. That is, the moment a certain variable has its value changed, it triggers a certain action. Look at the following example.

const [value, setValue] = React.useState('');

const handleChange = (event) => {
    setValue(event.target.value);
  };

React.useEffect(() => {
    async function loadClients() {
      setLoading(true);
      const response = await api.get('agendamentos', {
      headers: {
        value
      }
    });
  
      const temp = response.data.map((client) => {
        return {
          label: client.descricao,
          options: client.lojas
        }        
      })
  
      setContent(temp);
      setLoading(false);
    }

    if(value !== ''){
      loadClients();
    };
  }, [value])


<RadioGroup row aria-label="gender" name="gender1" value={value} onChange={handleChange}>
          <FormControlLabel value="trocas" control={<Radio color="default" />} label="Trocas" />
          <FormControlLabel value="estoques" control={<Radio color="default" />} label="Estoques" />
</RadioGroup>

I use useState to create variables but use useEffect to monitor it and call the API to load the new information.

  • Taking into account that its component is a Class component, it cannot use useEffect. Your answer would have more value by presenting a possible approach to the case of Class components as well.

0

You can add a state to store your search field:

  state = {
    protocolo: '',
  }

Using Xios you can pass the parameters this way:

const response = await api.get('solicitacao', { 
  params: { protocolo: this.state.protocolo }
}); 
// Saída: http://suaurl.com/solicitacao?protocolo=valor

Now you can create a input text updating the state.protocolo and create a button that calls its function that does the search

Browser other questions tagged

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