[REACT] this.state.array map is not a function

i’ve this situation

constructor(props){
        super(props);
        this.state = {
            card: null
        }
    }

then i’ve a function that update this.setState on an Array with some data i get from props but when on

render() {
 return(
   this.state.card.map((a, i) => {...})
)
}

i get this.state.card.map is not a function, how can i do it?

i need to update the state with data from props and then used map to create some Card

Set initial state to an empty array.

1 Like

But you’ve intialized card to null – how about initializing it to an empty array? []

Yeah, what @jenovs said. Beat me by that much!

same problem, “this.state.card.map is not a function”

Can you post your updated code?

 for(let i = 0; i < 5; i++){
            var newCard = this.state.card.push(this.props.tvSeries[i]);
            this.setState({
                card: newCard
            })
        }

it’s work, if i console.log(this.state.card) i get a Array with 5 object

push mutates the state directly, and although you’re calling setState immediately afterward, you risk unexpected behavior; the most likely is that the component simply won’t re-render, thinking the state hasn’t changed. Better to keep it non-mutating:

var newCard = [...this.state.card, this.props.tvSeries[i]];

.push() returns a length of the array, so newCard is not an array but integer. But because setState is asynchronous, it doesn’t update immediately, but when React feels like it. And because you mutate state directly when you console.log() you see that this.state.card is an array, but after that it gets updated and when you try to call .map() on integer you get an error.