Below is some logic to my current code that currently works as expected.
import react from 'react'
const [userBirthday,setUserBirthday] = useState()
function calculateAgeTurning() {
let ageToBe = new Date().getFullYear() - userBirthday.substring(0, 4);
return ageToBe;
}
function addBirthday(url) {
let newAge = calculateAgeTurning();
const newBirthday = {
id: uuidv1(),
Name: name,
AgeTurning: newAge,
image: url,
};
setAllBirthdays((prevState) => [...prevState, newBirthday]);
setIsAddBirthdayShown(false);
}
However I would like to store the users new age in some state.
What I am expecting is when the user presses a button it will call addBirthday() which then calls calculateAgeTurning(), updates my newAge State and I then set my AgeTurning to the users new age in my newBirthday object. But my state never updates and I constantly get 0 when I console log it. What am I not understanding?
import react from 'react'
const [userBirthday,setUserBirthday] = useState("")
const [userNewAge, setUserNewAge] = useState(0);
function calculateAgeTurning() {
let ageToBe = new Date().getFullYear() - userBirthday.substring(0, 4);
setUserNewAge(ageToBe);
}
function addBirthday(url) {
calculateAgeTurning();
const newBirthday = {
id: uuidv1(),
Name: name,
AgeTurning: userNewAge,
image: url,
};
setAllBirthdays((prevState) => [...prevState, newBirthday]);
setIsAddBirthdayShown(false);
}
console.log(newAge) //0