0

I am new in reactjs. I have problem while showing the result.Here is my code:

constructor (props) {
      super(props);
       this.state = {
         selectValue: '',
         yearsValue:'',
         months:''
       }
     this.setDataGroup = this.setDataGroup.bind(this);
   }

setDataGroup(e){
    var selectedType = e.target.value;
    if(selectedType == "quertly"){
       var quertlyData = [{
        data:"Jan-March",
        value:"1"
      },
      {
        data:"Apr-Jun",
        value:"2"
      },
      {
        data:"Jul-Sept",
        value:"3"
      },
      {
        data:"Oct-Dec",
        value:"4"
      }];
       this.setState({yearsValue:quertlyData});

I am showing the data like:

 render() {
 const data = JSON.stringify(this.state.yearsValue) || []
                  <div>
    {data.map((data, index) => {data})}
  </div>
}

My json looks like:

[{"data":"Jan-March","value":"1"},{"data":"Apr-Jun","value":"2"},{"data":"Jul-Sept","value":"3"},{"data":"Oct-Dec","value":"4"}]

Getting error .map is not function

Karan
  • 1,048
  • 2
  • 20
  • 38
  • 1
    why stringify? the data is an array already and I am assuming you don't want to get it as a string. Also your render method is mute, what do you expect from the mapping function, since the arrow function will return undefined for all elements – Icepickle Nov 13 '17 at 12:11
  • `yearsValue` is a `string`. `JSON.stringify` won't turn it into an array. – Hemerson Carlin Nov 13 '17 at 12:12

2 Answers2

3

yearsValue is a string and therefore using JSON.stringify won't help you.

Also, render method must return something:

constructor (props) {
  super(props);
  this.state = {
    selectValue: '',
    yearsValue: [],
    months:''
  }

  this.setDataGroup = this.setDataGroup.bind(this);
}
... 
render() {
  const { yearsValue } = this.state

  return (
    <div>
      {yearsValue.map((item, index) =>
        <div key={index}>{item.data}:{item.value}</div>
      )}
    </div>
  }
}
Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
2

Your data is in correct format. Initialize yearsValue as array in constructor like

this.state = {
  yearsValue: []
}

And then you can use yearsValue state in render like below

render() {
  return (
     <div>
       {this.state.yearsValue.map((d, index) => {
          return (
             <div key={index}>{d.data}</div>
          )
       })}
     </div>
  )
}
Elumalai Kaliyaperumal
  • 1,498
  • 1
  • 12
  • 24