Using setState to change multiple values within an array of objects -- ReactJS
You can pass an updater function to setState. Here's an example of how this might work.
The object returned from the updater function will be merged into the previous state.
const updateBubble = ({y, vy, ...props}) => ({y: y + vy, vy: vy + 0.1, ...props})
this.setState(state => ({bubbles: state.bubbles.map(updateBubble)}))
Change the updateBubble function to add bouncing and so on.
React setState multiple arrays based on index
You are creating a new names
and values
array with just one index populated in it. This is why you are overwriting other indices in the array
You could do something like this if you want to update only the specific indexes without mutation:
const { name, value } = e.target;
const [key, index] = name.split('-');
this.setState(prevState => ({
...prevState,
inputData: {
values: Object.assign([], {...prevState.inputData.values }, { [index]: value }),
names: Object.assign([], {...prevState.inputData.names }, { [index]: key })
}
}))
Another option is to take a copy of the prevState.inputData.values
using the spread syntax and update it's value at specific index and then set it to inputData
:
const { name, value } = e.target;
const [key, index] = name.split('-');
this.setState(prevState => {
const cloneValues = [...prevState.inputData.values],
cloneNames = [...prevState.inputData.names];
cloneValues[index] = value;
cloneNames[index] = key;
return {
...prevState,
inputData: {
values: cloneValues,
names: cloneNames
}
}
})
Change multiple key values and setState in React
try this:
handleclick = () => {
let players = this.state.players
players = players.map(player => {player.isVisible = true; return player;}))
this.setState({
players
})
}
How can I asynchronously update multiple objects in the same array in React?
just using a callback-style of updating your state would solve the issue:
setPoints((previousPoints) =>
previousPoints.map((p: Point) => {
if (p.id !== id) {
return p;
} else {
// if the target point has a position, change its elevation to undefined
if (newPointData.position) {
newPointData.elevation = undefined;
}
const updatedPoint: Point = update(targetPoint, {
$merge: newPointData,
})!;
return updatedPoint;
}
})
);
How to set multiple object value with special key on react js
Few things to be fixed
Your
item.data.id
is number ande.target.name
is string. To compare them without type comparison use!=
instead of!==
.The
else
block should be corrected as below.
handleChangeScore = (e, type, id) => {
const cScore = e.target.value;
this.setState((state) => {
return {
...state,
objData: state.objData.map((item) => {
if (item.data.id != e.target.name) return item;
else {
return { ...item, score: { ...item.score, [type]: cScore } };
}
})
};
});
};
Code Sandbox
How to change multiple properties of a state in react (at the same time)?
Its okay to call multiple setStates since React internally does batching before setState and hence will only call render
once. That said, the chances of you making a mistake in writing setState such that batching ignores a change or sets incorrect value are high(for instance you may call setState twice for the same key based on the previous value and might expect a result different from what you get). Hence its recommended that you call setState once after processing all the values
// Add card to active player
let playersClone = [...players];
playersClone[activePlayer].cards = [
...playersClone[activePlayer].cards,
openedCard
];
// Add any offered chips to active player
playersClone[activePlayer].remainingChips += offeredChips;
const playableCards = playableCards.filter(function(card) {
return card !== openedCard;
})
// Change active player
const nextPlayer = activePlayer === 0 ? 1 : 0;
// Reset offered chips to 0
// Reset opened card
// Remove card from deck
this.setState({
openedCard: null,
offeredChips: 0,
playableCards,
players: playersClone
}, () =>
this.calculateScore(activePlayer)
);
Related Topics
Barcode Scanner for Mobile Phone for Website in Form
How to Change Background Color of a Row on Checkbox Selection
How to Parse Through Local Json File in React Js
Passing Value from Java to JavaScript
How to Resolve Position:Fixed for a Bottom Toolbar on iOS (Iphone/Ipad)
Removing Currency Symbol and Replacing Comma With Point Using Pure JavaScript
Remove Specific Characters from String Jquery
Bootstrap Datepicker Set Default Date Not Working
Verify External Script Is Loaded
Angular 4:How to Get Index of Selected Value in a Datalist
Changing Svg Image Color With JavaScript
Javascript Json Parsing Error: Unexpected Token ' in Json At Position 1
How to Load a Font File in Vuejs and Webpack
Why Is It a Bad Practice to Return Generated HTML Instead of Json or Is It
How to Pass Arguments to Addeventlistener Listener Function
Angular 2 Not Updating Until Any Object Is Clicked