Answer the question
In order to leave comments, you need to log in
Why aren't hook values reassigned?
Why, when loading the page and outputting a variable to the console, films
I see its value from useState
, and not the result after setFilms(result);
(it is displayed simply []
, but an array from the API is needed).
My code:
import React, { useEffect, useState } from "react";
const App = () => {
const [films, setFilms] = useState([]);
useEffect(() => {
const Fetch = async () => {
const response = await fetch(
"https://kinopoiskapiunofficial.tech/api/v2.2/films/top?type=TOP_AWAIT_FILMS&page=1",
{
headers: {
"X-API-KEY": "i'm sorry :)"
}
}
);
const result = await response.json();
setFilms(result);
console.log(films);
};
Fetch();
}, []);
return <div></div>;
};
export default App;
Answer the question
In order to leave comments, you need to log in
Because setFilms is asynchronous.
To get updated films use useEffect
useEffect(() => {
// new films here
}, [films]);
import React, { useEffect, useState } from "react";
const App = () => {
const [films, setFilms] = useState([]);
useEffect(() => {
const Fetch = async () => {
const response = await fetch(
"https://kinopoiskapiunofficial.tech/api/v2.2/films/top?type=TOP_AWAIT_FILMS&page=1",
{
headers: {
"X-API-KEY": "i'm sorry :)"
}
}
);
const result = await response.json();
setFilms(result);
console.log(films);
};
Fetch();
}, [films]);
return <div></div>;
};
export default App;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question