Reputation: 1358
I have an array in the state. I am creating a method which adds a new row but how can i assign a dynamic id to the array in the setState?
This is what my state looks like:-
myArray: [
{ id:0, title:'Hello', function: 'none' }
]
And i have a method addRow
that creates new Array.
addRow = () => {
const rows = [...this.state.myArray, {id: '' ,value:'',options: []}];
this.setState({
myArray: rows
});
}
How can i create a new dynamic id onClick of that method?
Upvotes: 0
Views: 1402
Reputation: 2648
You can face asyc issues without functional setState, so you can do something like:
addRow = () => {
this.setState(previousState => {
const { myArray } = previousState
return { ...previousState, myArray: [ ...myArray, { id: myArray.length } ] }
});
}
For reference: https://reactjs.org/docs/faq-state.html#what-is-the-difference-between-passing-an-object-or-a-function-in-setstate
Upvotes: 0
Reputation: 317
There are 2 approaches which you can take:
Either add a counter variable this.setState({ count: this.state.count + 1 })
and increment it on every onClick.
OR
Use something like UUID import uuid from 'uuid'
which will generate a unique id for you to use.
Upvotes: 1
Reputation: 9149
Easiest way is using length of the current array.
addRow = () => {
const rows = [...this.state.myArray, {id: this.state.myArray.length ,value:'',options: []}];
this.setState({
myArray: rows
});
}
Upvotes: 3