Home > Blockchain >  How to make a function render something in an IF statement in ReactJS?
How to make a function render something in an IF statement in ReactJS?

Time:09-22

I have two async functions. One calls the other. And then the last one calls another function that has a logic and should print something in the HTML.

a (async) calls b (async) calls c (should print something)

function imprimeBlocos() {
  for (var i = 0; i < dados.state.subsistemas.length; i  ) {
    console.log(dados.state.subsistemas[i].nome); //I WANNA TRANSFORM THIS CONSOLE.LOG INTO A <p>
    for (var j = 0; j < dados.state.pessoas.length; j  ) {
      if (dados.state.pessoas[j].idsubsistema === dados.state.subsistemas[i].id) {
        console.log(dados.state.pessoas[j].nomecompleto); //I WANNA TRANSFORM THIS CONSOLE.LOG INTO A <p>
      }
    }
  }
}

async function selecionaPessoas() { //function b
  return Axios.post("http://localhost:3001/api/selecionaPessoas", {}).then((response) => {
    setPessoas(response.data);
    dados.setPessoas(pessoas);
    imprimeBlocos(); //calls function c
  });
}

async function selecionaSubsistemas() { //function a
  return Axios.post("http://localhost:3001/api/selecionaSubsistemas", {}).then((response) => {
    setSubsistemas(response.data);
    dados.setSubsistemas(subsistemas);
    selecionaPessoas(); //calls function b
  });
}

How do I do this?

CodePudding user response:

You should use a state to save the the data from the function and then where you want to render it, it'll update the tree.

const [data, setData] = useState([]);

function imprimeBlocos() {
  const data = data.state.subsistemas.map(({ id, nome }) => (
    <React.Fragment key={id}>
      <p>{nome}</p>
      {dados.state.pessoas.map(
        ({ idsubsistema, nomecompleto }) =>
          idsubsistema === id && <p>{nomecompleto}</p>
      )}
    </React.Fragment>
  ));

  setData(data);
}

Using a for loop, I have an initial empty data array, and I populate the array with the valid <p> element after the id check.

const [data, setData] = useState([]);

function imprimeBlocos() {
  const data = [];
  const subsistemas = data.state.subsistemas;
  
  for (let i = 0; i < subsistemas.length; i  ) {
    let children = [];
    const subsistemasItem = subsistemas[i];
    const pessoas = dados.state.pessoas;
    
    for (let j = 0; j < pessoas.length; j  ) {
      const pessoasItem = pessosas[j];
      
      if (pessoasItem.id === subsistemasItem.id) {
        children.push((
          <p>
            {pessoasItem.nomecompleto}
          </p>
        ));
      }
    }
    
    data.push((
      <React.Fragment key={subsistemasItem.id}>
        <p>{subsistemasItem.nome}</p>
        {children}
      </React.Fragment>
    ));
  }

  setData(data);
}

Then wherever you want to render it, you could do something like this

return (
  <div>
    {data}
  </div>
);
  • Related