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

128
Visualizações
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 à 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