Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
React Call Api after setState is done

Im stuck.

I need to make an API call and then again need to make another API call but with the data collected from the first one.

It work only for me if: Enter to my page -> go to vsc -> update code - for example add // somewhere and it's only thing that works.

Callbacks doesn't work or I'm just stupid :C

Is there possibility to do that synchronously?

import './App.css';

import A from './Components/A.js';
import React from 'react';

export class App extends React.Component {
    state = {
        a: {}
      };

      componentDidMount() {
        this.GetA();
      }
    
        GetA() {
        fetch("https://localhost:7138/Api/A/GetAll")
          .then((res) => res.json())
          .then((json) => this.setState( a => {return {a : json}}));
      }

    render() {
        return (
            <div>
                <A data={this.state.a}/>
            </div>
        )
    };
}

//

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.js";


export class A extends React.Component {
  state = {
    b: {}
  };

  componentDidMount() {
    this.GetB();//
  }

  GetB() {
    let entity = [];
    if (
      Object.keys(this.props.data).length !== 0 &&
      Object.keys(this.state.b).length === 0
    ) {
      this.props.data.map((o) =>
        fetch("https://localhost:7138/Api/Sygnature/GetSpecific", {
          method: "POST",
          body: JSON.stringify(o),
          headers: {
            "Content-Type": "application/json; charset=utf-8",
          },
        })
          .then((res) => res.json())
          .then((json) => {
            if (json !== undefined && json !== null) {
              json.map((x) => {
                entity.push(x);
              });
            }
          })
      );
      this.setState({ b: entity });
    }
  }

  render() {
    return (
      <div className="d-flex">
        <ul className="nav nav-tabs navbar-light bg-light">
          {Array.from(this.props.data).map((d) => (
            <li className="nav-item" id={d.id} key={d.name + d.id}>
              <a
                className="nav-link"
                data-bs-toggle="tab"
                href={"#" + d.name}
                style={{ textTransform: "uppercase", fontWeight: "bold" }}
              >
                {d.name}
              </a>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

export default A;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Just use componentDidUpdate instead of componentDidMount in the child component, and check if the props passed by the fetch of the parent are what you expect before making the next fetch.

export class A extends React.Component {
  state = {
    b: {}
  };

  componentDidUpdate() {
if(props.data)
    this.GetB();//
  }

  GetB() {
    let entity = [];
    if (
      Object.keys(this.props.data).length !== 0 &&
      Object.keys(this.state.b).length === 0
    ) {
      this.props.data.map((o) =>
        fetch("https://localhost:7138/Api/Sygnature/GetSpecific", {
          method: "POST",
          body: JSON.stringify(o),
          headers: {
            "Content-Type": "application/json; charset=utf-8",
          },
        })
          .then((res) => res.json())
          .then((json) => {
            if (json !== undefined && json !== null) {
              json.map((x) => {
                entity.push(x);
              });
            }
          })
      );
      this.setState({ b: entity });
    }
  }

  render() {
    return (
      <div className="d-flex">
        <ul className="nav nav-tabs navbar-light bg-light">
          {Array.from(this.props.data).map((d) => (
            <li className="nav-item" id={d.id} key={d.name + d.id}>
              <a
                className="nav-link"
                data-bs-toggle="tab"
                href={"#" + d.name}
                style={{ textTransform: "uppercase", fontWeight: "bold" }}
              >
                {d.name}
              </a>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

If you are not using react@18 you could also use UNSAFE_componentWillReceiveProps(nextProps) but componentDidUpdate is the right choice in these scenarios. Switching to Hooks makes it easier to manage the lifecycle since useEffect covers both componentDidUpdate and componentDidMount.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda