Edinho Rodrigues
Edinho Rodrigues

Reputation: 366

ReactJS - How to setSate in a map function

I got an object with another object inside and I need to render the DOM like this:

{ this.state.dates.map((date, i) =>
    <span className="event-date" key={i}>
     { date.date }
    </span>
    this.setState({tickets: date.tickets}) //Here, I need to update an object to map in another place
)}

./src/pages/Event/Event.js Syntax error: D:/YEAPPS/marketplace/pwa/src/pages/Event/Event.js: Unexpected token, expected , (54:32)

Click to see the object

Upvotes: 2

Views: 70

Answers (2)

Edinho Rodrigues
Edinho Rodrigues

Reputation: 366

I was able to solve like this:

                        {
                            this.state.tickets.map((ticket, i) => (
                                <div key={i}>
                                    <div className="row">
                                        <div className="col">
                                            <h3 className="ticket-name">{ ticket.name }</h3>
                                        </div>
                                    </div>
                                    {ticket.lot.map((lot, j) => 
                                        <div className="row" key={i}>
                                            <div className="col-8">
                                                <h5 className="lot-name">{ lot.name }</h5>
                                                <h6 className="lot-price">
                                                    R$ { lot.price.replace('.', ',') } <br />
                                                    <small>(R$ { lot.price.replace('.', ',') } + R$ { lot.price_tax.replace('.', ',') })</small>
                                                </h6>
                                            </div>
                                            <div className="col-4">
                                                <ChooseQuantity />
                                            </div>
                                        </div>
                                    )}
                                    <hr />
                                </div>
                                )
                            )
                        }

Upvotes: 0

andy mccullough
andy mccullough

Reputation: 9571

Do not call setState from within a render function, it will cause unnecessary rerenders, i.e. do not update the state with your tickets here

Set up your state within the component using other lifecycle hooks, e.g. componentDidMount, then simply map over your this.state.tickets.map(), or as you are already doing, this.state.dates.map()

Upvotes: 3

Related Questions