Lucio Zenir
Lucio Zenir

Reputation: 385

Why my this.state is null?

I'm new with React and i'm trying to render a json from a websocket.

Right now i'm able to get the json from the websocket using this :

 componentWillMount() {
    this.ws = new WebSocket('ws://10.77.0.79:1234')
    this.ws.onmessage = e => this.setState({data: Object.values((e.data))})
    this.ws.onerror = e => this.setState({ error: 'WebSocket error' })
    this.ws.onclose = e => !e.wasClean && this.setState({ error: `WebSocket error: ${e.code} ${e.reason}` })
  }

And then i need to map this json, right now i'm using this:

 render() {
  // this is my json from websocket
      var json2 = {"Auth":{"status":"true","user":"gesplan","pass":"root"}}

       var arr = [];
  Object.keys(json2).forEach(function(key) {
      arr.push(json2[key]);
    });

    return <ul>{arr.map(item => <MyAppChild key={item.status} label={item.status} value={item.user} pass={item.pass}  />)} {this.state.data} </ul>;

  }
}

class MyAppChild extends React.Component {
  render() {
    return <li>{this.props.label + " - " + this.props.value + this.props.pass  } </li>;
  }
}

With this i can render the values of the var json2.

How can i do it with my this.state.data? when i change json2 for this.state.data it return a null, but how can the state be null if i am rendering it normally?

Upvotes: 0

Views: 1402

Answers (1)

Blue
Blue

Reputation: 22911

Set your initial state to an empty array first. Append data when new data comes in:

constructor() {
    this.state = {
      data: []
    }
}

componentWillMount() {
    this.ws = new WebSocket('ws://10.77.0.79:1234')
    this.ws.onmessage = e => this.setState({
      data: [].concat(this.state.data, JSON.parse(e.data).Auth)
    })
    this.ws.onerror = e => this.setState({ error: 'WebSocket error' })
    this.ws.onclose = e => !e.wasClean && this.setState({ error: `WebSocket error: ${e.code} ${e.reason}` })
}

render() {
  return (
    <ul>
      {this.state.data.map(item =>
        <MyAppChild key={item.status} label={item.status} value={item.user} pass={item.pass}  />)
      }
    </ul>
  );
}

Upvotes: 1

Related Questions