0

I'm not sure how to modify the useEffect function (or use React's new Suspense component) to wait for all of the data to load in before rendering the components.

Here is the code that brings in the data from a Flask Backend:

import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:5000";

const [response, setResponse] = useState("");

  useEffect(() => {
    const socket = socketIOClient(ENDPOINT);
    socket.emit('test', {"name": "jim"})
    socket.on("test_client", data => {
      setResponse(data);
    }));
  }, []);

Here is the code that console.log's the JSON:

<p>Data: {console.log(props.data)}</p>

This returns the JSON in the console:

{content: {…}}
content:
     exchanges: (3) ["Deribit", "bybit", "BitMEX"]
     user_data: (10) [1, "testuser", "testuser", 
      "$5$rounds=535000$obwWzc1uoSI4MMFT$YruKioA8n321NDsX1UHXGtiY8rgfsBD.5z17kZ1UOnD", 
      "test@dwm.fund", "DWM", "United States", {…}, "1597353995233", 3]
     __proto__: Object
     __proto__: Object

When trying <p>Data: {console.log(props.data.content.user_data[1])}</p>, it returns the error Can't find property user_data of undefined.

I tried using the new Suspense component in React by wrapping my components in return with it, but I still received the same error.

Any help is appreciated, thank you.

Zero Cool
  • 2,541
  • 2
  • 8
  • 13
  • Hi, perhaps content is missing or there are multiple elements in a top-level array? – IronMan Oct 26 '20 at 23:53
  • im not sure what you mean by content is missing, it console.logs all of the json data i am moving in if i do `props.data`, but if i do `props.data.content.user_data[1]`, it returns undefined, even though it literally shows `props.data.content.user_data[1]` in the console if i do `props.data` – Zero Cool Oct 26 '20 at 23:58
  • this is more like a concern in your ui, please share more of your jsx code, you should be putting a spinner/loader when data has not yet loaded – diedu Oct 27 '20 at 01:22

1 Answers1

0

Adding a ternary operator to make the component reload once the data comes in solved it:

<p>Data: {props.data ? props.data.content.user_data[1] : "Data is loading..."}</p>

I guess the component was loading before the JSON could load the whole way through.

Zero Cool
  • 2,541
  • 2
  • 8
  • 13