Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

349
Vistas
React js setstate not working in nested axios post

I am trying to access the res.data.id from a nested axios.post call and assign it to 'activeId' variable. I am calling the handleSaveAll() function on a button Click event. When the button is clicked, When I console the 'res.data.Id', its returning the value properly, but when I console the 'activeId', it's returning null, which means the 'res.data.id' cannot be assigned. I just need to assign the value from 'res.data.id' to 'metricId' so that I can use it somewhere else in another function like save2() function. Does anyone have a solution? Thanks in advance

const [activeId, setActiveId] = useState(null);

useEffect(() => {}, [activeId]);

const save1 = () => {
      axios.get(api1, getDefaultHeaders())
        .then(() => {
          const data = {item1: item1,};

          axios.post(api2, data, getDefaultHeaders()).then((res) => {
            setActiveId(res.data.id);
            console.log(res.data.id); // result: e.g. 10
          });
      });
};

const save2 = () => {
  console.log(activeId); // result: null
};

const handleSaveAll = () => {
  save1();
  save2();

  console.log(activeId); // result: again its still null
};

return (
  <button type='submit' onClick={handleSaveAll}>Save</button>
);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This part of code run sync

const handleSaveAll = () => {
  save1();
  save2();

  console.log(activeId); // result: again its still null
};

but there you run async

axios.get(api1, getDefaultHeaders())
        .then(() => {

You can refactor your code to async/await like this:

const save1 = async () => {
      const response = await axios.get(api1, getDefaultHeaders());
      const response2 = await axios.post(api2, { item1: response.data.item1 }, getDefaultHeaders());
      return response2.data.id;
};

const save2 = (activeId) => {
  console.log(activeId); // result: null
};

const handleSaveAll = async () => {
  const activeId = await save1();
  save2(activeId);
  setActiveId(activeId);
  console.log(activeId); // result: again its still null
};

or to chain of promises, like this:


const save2 = (activeId) => {
  console.log(activeId); // result: null
};

const save1 = () => {
  return axios.get(api1, getDefaultHeaders())
    .then(({ data }) => {
      const data = {item1: item1,};
      return axios.post(api2, {item1: data.item1}, getDefaultHeaders())
    })
    .then((res) => res.data.id);
};

const handleSaveAll = () => {
  save1()
    .then((res) => {
      setActiveId(res.data.id);
      console.log(res.data.id); // result: e.g. 10
      return res.data.id;
    })
    .then(save2);
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda