Reputation: 117
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.
Upvotes: 1
Views: 6413
Reputation: 4464
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>
);
}
Upvotes: 2
Reputation: 681
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>
))
Upvotes: 0
Reputation: 177
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>
)
}
Upvotes: 0
Reputation: 755
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})
Upvotes: 0