Trying to display data in a view in React Js
, I have found an error that following the steps of the tutorial still persists:
this.state.users.map is not a function
The code is the following
import React, {Component} from 'react';
import {render} from 'react-dom';
import request from 'superagent';
class App extends Component{
constructor(){
super();
this.state = {
users: ""
};
}
componentDidMount(){
request.get('http://localhost:8080/api/usuarios')
.end((err, res) => {
const usuariosGet = JSON.parse(res.text).usuarios;
this.setState({
users: usuariosGet
});
});
}
render(){
var mostrarUsuarios = this.state.users.map((usuario, i) => {
return (<li key={i}>{usuario}</li>);
});
return(
<div>
<h1>Hola Mundo React JS</h1>
<ul>
{mostrarUsuarios}
</ul>
</div>
)
}
}
export default App;
What happens is that when the component is mounted
users
it is not an array but a string. When calledrender()
for the first time it will try to execute amap
but, since the strings do not contain such a method, it will fail. The solution should be enough to change your declaration in the constructor:EDIT
Regarding the error you mention in the comment, it is because what you receive is structured like this:
It is an array of objects with a property
Nombre
. The error is that you cannot render objects just like that, you must select some of their properties:The same happens to me:
Query:
has to be called
users:[]
Or it can be called something else, eg.
empresas:[]