0

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.

  • When are you calling the `setAssists` function? Also note that react batches state updates: console logging it right after setting the state may not reflect the most updated state. – Terry Jan 17 '22 at 21:03
  • completely empty or with '' values not filled as campusid: "" ? because that could mean alot different things – ndotie Jan 17 '22 at 21:24
  • Let me know so we close this one, hooks have their own behavior, of closure and async nature on updating – ndotie Jan 17 '22 at 21:25
  • campusid is not empty, but is not neccesary in this part, im gonna edit it –  Jan 17 '22 at 21:34

1 Answers1

0

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.

Graf-J
  • 81
  • 5
  • it works but only if i refresh the code 3 times –  Jan 17 '22 at 21:41
  • i tried also tu put in te useEffect in the second param: [assists] so it refresh but it makes an infinite loop and my memory crash (i think because the date changes each second) –  Jan 17 '22 at 21:43
  • I'm sorry, but this makes absolutly no sense to me. Maybe there is a bigger issue with your code which doesnt depend on this particular piece of code? – Graf-J Jan 18 '22 at 22:03