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

127
Vistas
React state not updating after API request

I am making a very simple store front react app that talks to a simple backend API that I made. I am trying to make a cart system that makes a POST request using the Axios library each time the page is loaded. The API will send back a cart object and it will have a unique ID. I want to store this ID in a state so that I can pass it to other pages to track the current card.

Here is the code for the function that handles making a POST request with Axios and storing that data in the currentCartID state:

const makeAPIPOSTRequestForCart = () => {
        setAPIRequestIsLoading(true);
        Axios.post('http://localhost:5512/carts/create').then((response) => {
            setCurrentCardID(response.data._id); // <-- THIS IS THE SET METHOD FOR THE STATE
            console.log('====================================');
            console.log('STATUS: ' + response.status);
            console.log('ID: ' + response.data._id);
            console.log('STATE OBJ: ' + currentCartID); // <--- PRINTS OUT NOTHING OR UNDEFINED
            console.log('====================================');
            setAPIRequestIsLoading(false);
        });
    };

This function is called each time the page is loaded with the useEffect hook like so:

useEffect(() => {
        makeAPIGETRequest();
        if (isCartMade === false) {
            makeAPIPOSTRequestForCart(); // <--- CALL TO POST FUNCTION RIGHT HERE
            setIsCartMade(true);
        }
    }, []);

The problem is each time I make this request the API is responding with a cart object and I can view the ID, however I cant seem to set the state to the current ID which is a string. Ive made sure that the type is correct however nothing is working. Whenever I try printing the state all I get is undefined or a blank line. It seems that the update state function is not working properly.

I am quite new to react so any help would be greatly appreciated! :)

about 4 years ago · Juan Pablo Isaza
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