0

I'm receiving a json string from server that looks like this: [{"foo":"123", "bar:456"},{"foo":"234","bar":"asd"}, ...] and I want create a list on my react page. I have to parse the string to turn it into an array of objects, I've tried doing that with JSON.parse(string) but it seems the only place I've succeeded to do that is in console.log, anywhere else and I get errors like Objects are not valid as a React child (found: object with keys {foo,bar}). I tried parse before setState, inside setState, after ... any suggestions?

The problem is not rendering an array of objects, it's saving a string as an array of objects inside a state so I can render it later.

This is the code I'm using:

import React, {Component} from 'react';
import {getMemberList} from '../../utils/client-api';
export default class Members extends Component {
  constructor() {
    super();
    this.state = {
      memberList: []
    };
  }
  memberList() {
    getMemberList().then(memberList => {
      this.setState({memberList});
      console.log(JSON.parse(memberList));
    });
  }
  componentDidMount() {
    this.memberList();
  }

  render() {
    const {memberList} = this.state;
    return (<div>
          {memberList}
        </div>);
  }
}
Trax
  • 1,445
  • 5
  • 19
  • 39
  • The problem is not rendering an array of objects, it's saving a string as an array of objects inside a state so I can render it later. – Trax Dec 15 '17 at 20:20
  • The error that you get is because React is trying is to Render an array expecting them to be JSX elements but instead it finds object, you need to stringify and render it within `
    ` tag
    – Shubham Khatri Dec 15 '17 at 20:23
  • Yes, that was the problem. Solution was `this.setState({memberList:JSON.parse(memberList)})` and then using map in render as expected. Thanks but still not a duplicate as my problem was using JSON.parse in the right place not mapping. – Trax Dec 15 '17 at 20:35

0 Answers0