Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js .push() is not a function

I'm a total rookie when it comes to React and this is most likely a simple issue, but it nearly drove me nuts.

The code is following:

import React, { Component } from 'react';

class Tile extends Component {
    constructor(props) {
        super(props);
        this.state = {
            priceLog: [],
            diff: 'equal'
        };
    }

    componentWillReceiveProps() {
        let log = this.state.priceLog;
        log = log.push(this.props.price);
        this.setState({ priceLog: log });
        console.log(this.state.priceLog);
    }

    render() {
        return (
            <div className="Tile">
                Company: {this.props.name}<br/>
                Price: {this.props.price}
                <div className={this.state.diff}></div>
                <button id={this.props.id}>Details</button>
            </div>
        );
    }
}

export default Tile;

I get "Unhandled Rejection (TypeError): log.push is not a function" when the component is rendered. All properties passed to the component are strings.

like image 396
David Gevorgyan Avatar asked Nov 29 '22 13:11

David Gevorgyan


2 Answers

Besides the answer from @CD, you do not want to directly manipulate a state outside the designated setState method. In this case you could use concat to return a new array and assign that to the state variable. Something like this

this.setState({ priceLog: this.state.pricelog.concat(this.props.price)});

And your second call to the console.log might not deliver the desired results since setState is an asynchronous call. If you want to access the new state variable you have to use a callback like this

 this.setState({
     priceLog: this.state.pricelog.concat(this.props.price)
 }, () => console.log(this.state.pricelog));
like image 176
Murat Karagöz Avatar answered Dec 05 '22 05:12

Murat Karagöz


push returns the new length of the array so replace:

log = log.push(this.props.price);

with:

log.push(this.props.price);   
like image 27
CD.. Avatar answered Dec 05 '22 04:12

CD..