David Gevorgyan
David Gevorgyan

Reputation: 332

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.

Upvotes: 6

Views: 23317

Answers (2)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37604

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));

Upvotes: 15

CD..
CD..

Reputation: 74156

push returns the new length of the array so replace:

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

with:

log.push(this.props.price);   

Upvotes: 10

Related Questions