Can't save data from Directus in React state

I’m trying to fetch and use Directus API data.

I’m doing all by textbook, and yet it won’t assign received object:

import React, { useState, useEffect } from "react";
import { createDirectus, rest, readItems } from '@directus/sdk';

const Home = () => {
  const [games, setGames] = useState([]);

  useEffect(() => {
    fetchNewsGames();
  }, []); 

const fetchNewsGames = async () => {
   
    const response = await axios.get(
      "http://localhost:8055/items/stockholm_games"
    ); 

/* tried this as well, it returns in "response", needed objects, in console.log, but still can't assign them !!! ):

    const client = createDirectus('http://localhost:8055').with(rest());
 const response = await client.request(readItems('stockholm_games')); */

   setGames(response.data.data)
   console.log("in console:", response);
   console.log("saved in state is:", games);


// to get properties..
console.log("list of all: "+ 
  games.map(item => (
    item.title
   ))
 )


  };

Only at second try, it populates, only if I set
}, [games]);

Well clearly that screenshot doesnt match the code you’re showing us, because the screenshot says your first line to the console is “use it as”, and in the code it’s “in console:”. You sure you’ve compiled your code again after making changes?

somehow it magically fixed itself, when I try to access state variable outside of useEffect, it shows normal value.
And if I call inside of useEffect, it doesn’t.

const Home = () => {
  const [games, setGames] = useState([]);

  useEffect(() => {
    fetchNewsGames();
  }, []);

  const fetchNewsGames = async () => {
    try {
      const response = await axios.get(
        "http://localhost:8055/items/stockholm_games"
      );



      // set variable.
      setGames(response.data.data);

    } catch (error) {
      console.error("Error fetching games:", error);
    }
  };


  console.log(games);
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.