Home > OS >  React - On initial load, my state array is only saving the last element
React - On initial load, my state array is only saving the last element

Time:09-16

I have a React JS project and the following problem:

In the state, I have a decorators array and a polyPaths array, i.e:

this.state = {
    decorators = [],
    polyPaths = [],
}

In my render method, I have the following piece of code:

{this.state.polyPath.map((polyline, index) => {
                            return (
                                <PolylineDecorator
                                    patterns={arrow_blue}
                                    positions={polyline}
                                    color={"blue"}
                                    opacity={0.5}
                                    key={index}
                                    addDecorator={this.addDecorator}
                                    currDecorators={this.state.decorators}
                                    checkIfSamePath={this.checkIfSamePath}
                                />
                            );
                        })}

This will map over the polylines and render a poly line decorator.

In the PolylineDecorator component, I call the following method:

addDecorator = (dec) => {
        // Add decorator to state
        this.setState({
            decorators: [...this.state.decorators, dec]
        })
    }

Now my problem is that for some reason, if there are already 2 existing items in the polyPaths, only the second decorator will be saved to the state i.e: decorators will only have 1 element..

I'm not sure why this happens (maybe because it's setting the state again too quickly?), and what could I possibly do about it?

I know that the addDecorator function does indeed get called twice, with each respective decorator, it just only saves the last one??

Thanks

CodePudding user response:

addDecorator = (dec) => {
        // Add decorator to state
        this.setState({
            decorators: [...this.state.decorators, ...dec]
        })
    }

use the spread operator on both arrays otherwise you just put the new array directly inside the old array

or if you want to put another a brand new array do


addDecorator = (dec) => {
        // Add decorator to state
        this.setState({
            decorators: dec
        })
    }

  • Related