Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: this.state.data.map is not a function

I am new to React, have seen some of the similar issues, but didn’t find why this happens. I am getting an “Uncaught TypeError: this.state.data.map is not a function”. Here is the code. Please, help to find what is the problem.

class Audienses extends React.Component {

    constructor (props)
    {
        super(props);

        this.state = {
            data: ''
        };

        this.loadFromServer = this.loadFromServer.bind(this);
        this.childeDelete = this.childeDelete.bind(this);
        this.childeEdit = this.childeEdit.bind(this);

    }

    loadFromServer () {
        var xhr = new XMLHttpRequest();
        xhr.open('get', this.props.url, true);
        xhr.onload = function() {
            var data = JSON.parse(xhr.responseText);
            this.setState({ data: data });

        }.bind(this);
        xhr.send();
    }

    componentDidMount() {
        this.loadFromServer();   
    }


     render () {

         var audienses = this.state.data.map((value, index) => (
           <OneElement key={value.id} audience={value.audience} description={value.description} />
        ));

        /* or like this
         var audienses = this.state.data.map(function(s) {
             <OneElement key={s.id} audience={s.audience} description={s.description} onDeleteClick={this.childeDelete} oneEditClick={this.childeEdit} />
         }).bind(this);
        */
         return
        <div>
            <h1>Audiences</h1>
            <table id="services">
                <tr>
                    <th>Audience</th>
                    <th>Description</th>
                    <th></th>
                    <th></th>
                </tr>
                <tbody>
                   {audienses}
                </tbody>
            </table>
        </div>;
    }
}
like image 475
Ang Avatar asked Sep 10 '25 08:09

Ang


2 Answers

Your initial data state is String., String does not have method .map, you need change your initial state from '' to []

this.state = {  data: [] };
like image 192
Oleksandr T. Avatar answered Sep 13 '25 00:09

Oleksandr T.


.map is not applicable to a String object. Consider changing 'data' to an array. .map is a method that calls a function on every element of an array.

like image 26
JFAP Avatar answered Sep 12 '25 23:09

JFAP