1

I am new to React.I am facing this error.I have the code which is pasted below.Please help get out of this error.

import React from 'react';
import { Card} from 'semantic-ui-react';
import axios from 'axios';

export default class PersonList extends React.Component {
state = {
    persons: []
}

componentDidMount() {

axios.get(`http://localhost:8080/locations`)
  .then(res => {
    const persons = res.data;
    this.setState({ persons });
  })
}

render() {
   return (
    <div class="ui stackable two column grid">
     { this.state.persons.map(person =>  
       <div class="column">
        <Card
          header={person.LOCATION}
        />
      </div>)
     }
    </div>
   )
 }
}

The error message is pasted below

TypeError: this.state.persons.map is not a function
PersonList.render
C:/Users/user/Desktop/src/Sample.js:22
19 | render() {
20 |   return (
21 |       <div class="ui stackable two column grid">
> 22 |        { this.state.persons.map(person =>  
23 |          <div class="column">

Output of console.log('data', res.data):

{LOCATION: "CHINA9, SWEDEN9, CANADA9, austin, ", searchKey: {…}}

I request anyone to figure me out this error.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
kingkong
  • 107
  • 3
  • 9
  • 1
    that means the data that you are getting from server is not an array, check that by `console.log(res.data)`, it should be `[]` – Mayank Shukla Feb 28 '18 at 07:28
  • {LOCATION: "CHINA9, SWEDEN9, CANADA9, austin, ", searchKey: {…}} --- is the output of res.data . Will the locations be accesed in above code I mean will I be able to print CHINA9 etc. – kingkong Feb 28 '18 at 07:57
  • that is an object that' why it was throwing error, how you want to print these values, expected output? – Mayank Shukla Feb 28 '18 at 07:58
  • I want to print them in the Cards as you see in the above code ...A card for every location. Actually I am returning a Map from the server. Any idea how to return JSON from Spring Boot so that I can access here in React. – kingkong Feb 28 '18 at 07:59
  • @dps plz check updated answer. which will display LOCATION in card header. – Javed Shaikh Feb 28 '18 at 08:48

4 Answers4

2

You can create an array from the LOCATION string using .split(',') :

function render() {
  const locationArr = this.state.persons.LOCATION
    ? this.state.persons.LOCATION.split(',')
    : [];
  return (
    <div className="ui stackable two column grid">
      {locationArr.map((location) => {
        if (location !== ' ') {
          return (
            <div className="column">
              <Card header={location} />
            </div>
          );
        }
        return null;
      })}
    </div>
  );
}
Dyo
  • 4,429
  • 1
  • 15
  • 30
  • I get the output but it prints a blank card as well.How do I get rid of that? For your reference {LOCATION: "CHINA9, SWEDEN9, CANADA9, austin, ", searchKey: {…}} – kingkong Feb 28 '18 at 09:20
  • I edited my answer to handle the blank result but your server shouldn't send that. – Dyo Feb 28 '18 at 09:28
0

create constructor and declare your state

constructor(props){
     super(props);
     state = {
        persons: ""
     }
   }

change state update to

axios.get(`http://localhost:8080/locations`)
  .then(res => {
    this.setState((prevState) => ({ persons : res.data.LOCATION }));
  })
}

render method

this.state.persons.split(",").map((person, index) => (
    <div class="column" key={index}>
        <Card
          header={person}
        />
      </div>
))
Javed Shaikh
  • 663
  • 7
  • 16
0

you set this.state.persons to res.data which is probably an object.. you cannot use map on an object...

instead you maybe want to push the the object to an array of objects. like this:

let persons = this.state.persons.slice()
persons.push(res.data)    
this.setState({persons})
Egor Egorov
  • 705
  • 3
  • 10
  • 22
0
  • First of all make sure that you are getting data from the server in the form of array because map only works on array.
  • Secondly correct your code structure little bit. render() { let { perons } = this.state.perons; if (perons.length == 0) { return ( <div><h3>Loading data...</h3></div> ) } return ( <div class="ui stackable two column grid"> { persons.map(person =>{ return(
    <div class="column"> <Card header={person.LOCATION} /> </div> ) }); } </div> ) }
Asad Marfani
  • 177
  • 3
  • 13
  • Actually I am returning a Map from the server. Any idea how to return JSON or as you say 'array' from Spring Boot so that I can access here in React. – kingkong Feb 28 '18 at 08:44
  • Well i didn't use Spring Boot framework but you can **refer to these links** [https://stackoverflow.com/questions/44839753/returning-json-object-as-response-in-spring-boot](https://stackoverflow.com/questions/44839753/returning-json-object-as-response-in-spring-boot) and [https://stackoverflow.com/questions/32905917/how-to-return-json-data-from-spring-controller-using-responsebody/35822500#35822500](https://stackoverflow.com/questions/32905917/how-to-return-json-data-from-spring-controller-using-responsebody/35822500#35822500). Hope it will be helpful. – Asad Marfani Feb 28 '18 at 09:01