How would I update the stock number of a car with a given index using an increment function? I'm assuming I need to use setState but I'm not sure how to implement that. If I use setState inside the increment function will my react component re-render?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
"manufacturer": "Toyota",
"model": "Rav4",
"year": 2008,
"stock": 3,
"price": 8500
},
{
"manufacturer": "Toyota",
"model": "Camry",
"year": 2009,
"stock": 2,
"price": 6500
},
]
};
}
increment(index)
{
//Need to increment the stock number by 1 here
}
render() {
return (
<table>
<tr>
<th>manufacturer</th>
<th>model</th>
<th>year</th>
<th>stock</th>
<th>price</th>
<th>option</th>
</tr>
<tr>
<td>{this.state.cars[0].manufacturer}</td>
<td>{this.state.cars[0].model}</td>
<td>{this.state.cars[0].year}</td>
<td>{this.state.cars[0].stock}</td>
<td>${this.state.cars[0].price}.00</td>
<td>
<button onClick={this.increment(0)}>Increment</button>
</td>
<td>
<button>Decrement</button>
</td>
</tr>
<tr>
<td>{this.state.cars[1].manufacturer}|</td>
<td>{this.state.cars[1].model}</td>
<td>{this.state.cars[1].year}</td>
<td>{this.state.cars[1].stock}</td>
<td>${this.state.cars[1].price}.00</td>
<td>
<button onClick={this.increment(1)}>Increment</button>
</td>
<td>
<button>Decrement</button>
</td>
</tr>`your text`
</table>
);
};
}
ReactDOM.render(<App />, document.getElementById("app"))
I'm assuming I need to use setState in my increment function but how would I do that?
CodePudding user response:
Yes it will be re-rendered.
const newCar = this.state.car;
newCar[index].stock = 1;
this.setState(newCar);
It will make re-render since the newCar should be new object.
If it is not working, you can change the reference of array.
like this
const newCar = {...this.state.car};
CodePudding user response:
You can do as below:
function increment(index){
let updateValue = this.state.cars;
updateValue[0].stock ;
this.setState({
cars: [...updateValue]
})
}
And yes each time you try to update value on state your component re-render
CodePudding user response:
You are right, you do this with setState
this function can take in a function which receives the current state.
With the index you pass in to the increment
function you can map over the cars
in the state. If the idx
of the item in the array is equal to the index
you pass in the function you can update the stock.
function increment(index) {
this.setState((state) => {
const newCars = state.cars.map((car, idx) => {
if (index !== idx) return car;
return {
...car,
stock: car.stock 1,
};
});
return {
...state,
cart: newCars,
};
});
}