Home > front end >  React handleSubmit form - how to ensure that methods within the handlesubmit method will only be exe
React handleSubmit form - how to ensure that methods within the handlesubmit method will only be exe

Time:09-17

I have a search form that, when submitted, it triggers the handleSubmit() function and inside the handleSubmit() function I have I have 3 methods whose execution depends on each other, what I want is to ensure that each method is executed one by one inside the handleSubmit method

what I want is to ensure that the carregarCursos() method is only executed when the carregarDisciplinas() method is executed and that the carregarPlanoCurso() method is executed only when the carregarCurso() method is executed

function handleSubmit({
    anoLetivo1,
    curso1,
    unidadeCurricular1
  }) {

    carregarDisciplinas().then((value) => {
      setResPesquisaDisciplina(
        value.filter((disciplina) => disciplina.nome === unidadeCurricular1)
      );
    });

    carregarCursos().then((value) => {
      setResPesquisaCurso(value.filter((curso) => curso.nome === curso1));
    });

    carregarPlanoCurso().then((value) => {
      setResPesquisaPlano(
        value.filter((plano) => plano.id_disci === resPesquisaDisciplina[0].id)
      );
    });

}

Below how the methods and variables are being declared:

  const [resPesquisaDisciplina, setResPesquisaDisciplina] = useState([]);
  const [resPesquisaCurso, setResPesquisaCurso] = useState([]);
  const [resPesquisaPlano, setResPesquisaPlano] = useState([]);
  async function carregarCursos() {
    const response = await api.get('cursos/');

    return response.data;
  }

async function carregarPlanoCurso() {
    const response = await api.get(`cursos/${resPesquisaCurso[0].id}/plano`);
    return response.data;
  }
async function carregarDisciplinas() {
    const response = await api.get('disciplinas/');

    return response.data;
  }

CodePudding user response:

You can create an async function and fetch all data you need, something like this:

async function loadAllData() {
    const cursos = await carregarCursos();
    const planos = await carregarPlanoCurso();
    const diciplinas = await carregarDisciplinas();
    return { cursos, planos, diciplinas }
}

loadAllData().then(({ cursos, planos, diciplinas }) => {
    //...All the setData functions 
});

CodePudding user response:

I managed to solve the problem with useEffect, I made the carregarPlanoCurso() method be called only when the variable resPesquisaCurso changes size, useEffect was declared outside the scope of handleSubmit:

useEffect(() => {
    if (resPesquisaCurso.length !== 0) {
      carregarPlanoCurso().then((value) => {
        setResPesquisaPlano(
          value.filter(
            (plano) => plano.id_disci === resPesquisaDisciplina[0].id
          )
        );
      });
    }
  }, [resPesquisaCurso]);
  • Related