Hi im trying to setting states in react but they dont update correctly, i have:
const [campusName, setCampusName] = useState("");
const [assists, setAssists] = useState({
name:"",
hour: "",
day: "",
month: "",
year: "",
studentid: "",
});
const [date, setDate] = useState({
day: "",
month: "",
year: "",
hour: "",
});
useEffect(()=>{
getData();
}, [])
const getData = async() =>{
//campus name
const campusResponse = await fetch("http://localhost:2000/info/campus/"+params.campusid);
const campusData = await campusResponse.json();
setCampusName(campusData.name);
//date
const date = new Date();
setDate({
day: date.getDate(),
month: date.getMonth()+1,
year: date.getFullYear(),
hour: `${date.getHours()}:${date.getMinutes()}`,
});
settingAssistence();
}
const settingAssistence = () => {
setAsists({
name: campusName,
campusid: params.campusid,
hour: date.hour,
day: date.day,
month: date.month,
year: date.year,
studentid: params.studentid,
})
console.log("result", asissts);
}
the console.log prints the assists object empty, but if i refresh the page 3 times it works, how can i set the states correctly? the fetch with http://localhost:2000/info/campus/ also works good and give me the correct data, but when i set it into the hook is not updating correctly.
Just add a small button to your UI to log the assists state. The Hooks take their time to execute and if you log your result right after setting the state is doesnt show the actual value.