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! 🙂