D
D
Daniel Chistyakov2021-04-13 23:47:28
React
Daniel Chistyakov, 2021-04-13 23:47:28

Why aren't hook values ​​reassigned?

Why, when loading the page and outputting a variable to the console, filmsI 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

2 answer(s)
Y
y0u, 2021-04-14
@danielchistyakov

Because setFilms is asynchronous.
To get updated films use useEffect

useEffect(() => {
    // new films here
}, [films]);

A
Alice, 2021-04-14
@w3bsmes

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 question

Ask a Question

731 491 924 answers to any question