0

I am recieving an object from a websocket,

const client = new    
W3CWebSocket("ws://ABCD:9080/user");

I want to access values from the object and display it on the browser.

const [object, setObject] = useState(""); 
   

    client.onopen = () => {
      console.log("Connected");
    };

    client.onmessage = (e) => {
      const newObj = JSON.parse(e.data); 

Next I want to set new state with the object I recieved.

setObject(newObj.data);

Next, I want to map through that object and access the values inside it:

    return (
      <div className="App">
        <Navbar />
        {Object.keys(object).map((objKey, index) => (
            <div key={index}>
              <p> {objKey} : {object[objKey]}</p>
            </div>
        ))}
        <DataTable object = { object } />
      </div>
    );

How do I map through the object and display the values I need on the browser. I think I'm missing something since nothing is getting displayed n my browser.

1
  • 1
    Please do not edit your question to apply what the answers are suggesting since it invalidates existing answers. If the answers have fixed part of the issue, but you're getting a new issue, please consider accepting the answer and asking a new question regarding the new issue. Commented Aug 24, 2021 at 15:13

2 Answers 2

2

You have used Object.keys(setObject) where, setObject is a function, and will return an empty array []. Use Object.keys(object) instead

return (
  <div className="App">
    <Navbar />
    {Object.keys(object).map((objKey, index) => (
        <div key={index}>
          <p> {objKey} : {object[objKey]}</p>
        </div>
    ))}
    <DataTable object = { object } />
  </div>
);
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting this error now " TypeError: Cannot convert undefined or null to object"
That might be because while settingsetObject(newObj.data), newObj.data can be either null or undefined. console.log(newObject.data) before setting the state to see newObj's value
1

You are passing setObject instead of object in Object.keys()

5 Comments

This doesn't appear to be an answer. Please use the comments section for this.
I believe it's due to SO's silly restriction which only allow comment section for user with 50 reputation and above @BrianThompson
I'm sure that's true, but it doesn't make it ok. After the edit it does appear to be answering the question though.
I'm getting this error now " TypeError: Cannot convert undefined or null to object"
The answer was already there, but with a remark before. If it is against the rule, I'll avoid that in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.