this.state.users.map is not a function

4

Trying to show 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 as follows

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;

    
asked by Pedro Miguel Pimienta Morales 23.02.2018 в 19:11
source

1 answer

3

What happens is that when you mount the component users is not an array but a string. When calling render() for the first time it will try to execute a map but, since the strings do not contain such a method, it will fail. The solution should suffice to change your declaration in the constructor:

this.state = {
    users: []
};

EDIT

Regarding the error that you mention in the comment, it is because what you receive is structured as follows:

[
    { Nombre: 'Juan' },
    { Nombre: 'Isaac' }
]

It is an array of objects with a Nombre property. The error is that you can not render objects just like that, you must select some of their properties:

var mostrarUsuarios = this.state.users.map((usuario, i) => {
    return (<li key={i}>{usuario.Nombre}</li>);
});
    
answered by 23.02.2018 / 19:29
source