Error in map: this.state.filmes.map is not a Function. I’m not being able to access the Results information. Could you help me?

Asked

Viewed 367 times

-2

import React, { Component, Fragment } from 'react';
import $ from 'jquery';

export class ListaFilmes extends Component{


    constructor() {
        super();
        this.state = {
            filmes: [],
        }

    }

    componentDidMount() {


        $.ajax({
            url: "http://localhost:3000/filmes?page=1",
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json',

            success: function (resposta) { 

                this.setState({filmes: resposta});
                console.log(resposta);




            }.bind(this),
            error: function (data) {

                console.log(data)
            }
        });
    }

    render(){
        return(
            <div>

                {this.state.filmes.map((item) =>
                 <li key={item.results}>{item.results}</li>


                )} 

            </div>

        )
    }
}

inserir a descrição da imagem aqui

  • Nunhuma of these solves your problem? It seems that this is a common error in React

1 answer

-1


What happens is that in its state the "movies" is an array, but the return of its API is an object. As you are assigning the API response to the "movies" state, you end up getting this error from "map is not a Function", since "map" applies to arrays.

In your object received from the API, you have "Results", and "Results" is an array. You must assign its value to "movies".

Your query would look like this:

componentDidMount() {

$.ajax({
    url: "http://localhost:3000/filmes?page=1",
    type: 'GET',
    dataType: 'json',
    contentType: 'application/json',
    success: function (resposta) { 
        this.setState({filmes: resposta.results});
        console.log(resposta);
    }.bind(this),
    error: function (data) {

        console.log(data)
    }
});

}

  • I put as you asked!! It worked!!! Thank you very much msm, I spent a long time trying to find the mistake!! Salvouuu me

Browser other questions tagged

You are not signed in. Login or sign up in order to post.