0

JSON.Parse throws errors! I am currently passing data in through a socket, and I can successfully read the data, but using it as a json object is giving me a lot of troubles. Here is my code

import React, { Component } from "react";
import socketIOClient from "socket.io-client";
class App extends Component {
  constructor() {
    super();
    this.state = {
      response: false,
      endpoint: "http://127.0.0.1:4001"
    };
  }
  componentDidMount() {
    const { endpoint } = this.state;
    const socket = socketIOClient(endpoint);
    socket.on("message", mi => this.setState({ response: mi }));
  }
  render() {
    const { response } = this.state;
    const data = response.cc
    return (
      <div style={{ textAlign: "center" }}>
          {
            JSON.stringify(data)
          }
      </div>
    );
  }
}
export default App;

I am using jsonfile to read the file and check for changes, if so, push them through. Without using the JSON.stringify function, the page I am currently working in throws an error " If you meant to render a collection of children, use an array instead."

5
  • mention the full data, and error you mentioned, is very common, you will find many solutions, check "How to render object properties in ReactJS". Commented Jan 27, 2018 at 8:45
  • So the data is api.coinmarketcap.com/v1/ticker this. I am trying to learn sockets and found this to be a good starting point. Will search and see what I find, thank you Commented Jan 27, 2018 at 8:50
  • Check this question stackoverflow.com/questions/43721168/…, you might not need to stringify JSON data and render Commented Jan 27, 2018 at 8:55
  • @ImranChowdhry its an array, so for each item what property you want to render? Commented Jan 27, 2018 at 9:12
  • @MayankShukla I just want the coin rank name and price_usd for the coins in the list. I've gotten the map function to work while manually loading the json file in the same component, but it doesn't update anything. This way I have updates values but I can't render it the way I want Commented Jan 27, 2018 at 9:15

1 Answer 1

1

Reason why it is throwing the error is, because the initial value is boolean, and you are trying to run loop on any property of boolean, Here:

const { response } = this.state;   // response = false
const data = response.cc           // data will be undefined
data.map(.....)                    // can't read property map of undefined

Solution:

1- One option is skip the rendering until you didn't get the data from server.

Like this:

render(){
    if(!this.state.response)
        return <div>Loading...</div>

    return(....)
}

2- Other option is, define the response as an object instead of boolean in the state, and use || [] with response.cc.

Like this:

constructor() {
    super();
    this.state = {
      response: {},
      endpoint: "http://127.0.0.1:4001"
    };
}

Render the array using #array.map, Like this:

render() {
    const { response } = this.state;
    const data = response.cc || [];
    return (
        <div style={{ textAlign: "center" }}>
        {
            data.map(el => (
                <div key={el.id}>
                    <p>Rank: {el.rank}</p>
                    <p>Price: {el.price_usd}</p>
                </div>
            ))
        }
        </div>
    );
}
Sign up to request clarification or add additional context in comments.

4 Comments

WOW! Thank you so much!! This worked! Why does the "|| [ ]" allow it to work? Everything else made sense and I am very much appreciative for your help
because if response={}, then response.cc will be undefined, || [] will assign the default value as an blank array to response.cc, and it will work.
Ah, ok makes sense. Very helpful to have a fresh pair of eyes :)
glad, it helped you :)

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.