Technologies:
Tolerim
2 hours ago
Why does this program keep giving me the same old input every time I run it?
I am currently studying hooks, and the
useState
method is causing me confusion. My aim is to set an initial value in the form of an array to the state. The set
method in useState
is not working for me, with and without the spread syntax. Additionally, I have an API running on a separate PC, which I would like to call and use its data to populate the initial state. Referencing the code below, I attempted to do this but I am encountering issues with setMovies(result)
and setMovies(...result)
not functioning correctly. My intention is for the result
variable to be added to the movies
array.Answers(1)
Tolerim
2 hours ago
Verified Answer
The issue with the code is that setMovies is an asynchronous function, it does not change the state immediately. Therefore, when console.log("movies =", movies) is executed, the state has not yet been updated. Instead, you can add a console.log inside the useEffect hook after setMovies to see the updated state:
useEffect(() => {
(async function() {
try {
const result = [
{
category: "cat1",
description: "desc1",
id: "1546514491119",
name: "randomname2",
photo: null,
rating: "3"
},
{
category: "cat2",
description: "desc1",
id: "1546837819818",
name: "randomname1",
rating: "5"
}
];
console.log("result =", result);
setMovies(result);
} catch (e) {
console.error(e);
}
})();
}, []);
useEffect(() => {
console.log("movies =", movies);
}, [movies]);
Also, you do not need to use the spread syntax with setMovies since you are assigning a whole new array to the state variable. So instead of setMovies(...result), you can simply use setMovies(result).