0

I have react app requeting a flask server, I can return the objects but when I assing the state to a new variable it log undefined, even though I am able to log it

  const [characters, setCharacters] = useState([]);
  useEffect(() => {
    const getData = async () => {
      await fetch("http://127.0.0.1:6789/api/load_img_data")
        .then((res) => res.json())
        .then(
          (result) => {
            const arrayOfObj = Object.entries(result.imgData).map((e) => e[1]);
            setCharacters(arrayOfObj);
          },
          (error) => {}
        );
    };
    getData();
  }, []);

 console.log(characters); ## it works fine and log the object on the console

  const columnsFromBackend = {
    ["1"]: {
      name: "Terminator Group",
      items: characters,   ## doesn't work when I map over it as it will be always empty 
}
}

so my question what it the best way to assign a state to variable? thanks

Yusuf
  • 2,295
  • 7
  • 15
  • 34
  • This is happening because your hooks are not getting updated when you are calling columnsFromBackend. Generally I use setTimeout around the set method of the hook to resolve the issue or you can assign the values to columnsFromBackend in your async method after you are setting charachter hook – bhuwan saoji Jul 26 '22 at 10:21
  • can you explain with example please? @bhuwansaoji – Yusuf Jul 26 '22 at 10:24

1 Answers1

0

You can declare your columnsFromBacked and initialize it as empty object.After you data from api is stored in the hook, then you can assign the appropriate values to columnsFromBacked Solution 1

let columnsFromBackend= {}
const [characters, setCharacters] = useState([]);
      useEffect(() => {
        const getData = async () => {
          await fetch("http://127.0.0.1:6789/api/load_img_data")
            .then((res) => res.json())
            .then(
              (result) => {
                const arrayOfObj = Object.entries(result.imgData).map((e) => e[1]);
                setCharacters(arrayOfObj);
                columnsFromBackend = {
                  ["1"]: {
                    name: "Terminator Group",
                    items: characters
                  }
                }
              },
              (error) => {}
            );
        };
        getData();
      }, []);
            
    }

Solution 2 You can implement useEffect hook with dependency on character hook.

sample code

useEffect(()=>{
   columnsFromBackend = {...} //your code
}, [character]); 
  • 1
    this returning an empty object when I console.log(columnsFromBackend) and I have changed const to let in line one of your answer – Yusuf Jul 26 '22 at 10:42
  • I have updated by code please see if this works for you. If it doesnt please let me know where are you trying to access the variable columnsFromBackend – bhuwan saoji Jul 26 '22 at 11:22