React Js, adding new object to an array
For the view to update, you must call setState, and not just push an item to the array, you can easily do it using the spread syntax:
addItem(e){
e.preventDefault();
const newItemInput = this.state.newItemInput;
const newRadioValue = this.state.selectedValue;
const obj = {'item':newItemInput, 'columnType':newRadioValue};
this.setState({
buyItems: [...this.state.buyItems, obj]
});
console.log(this.state.buyItems);
}
An alternative would be create a copy of the old array, push the new item and proceed to set the state:
addItem(e){
e.preventDefault();
const newItemInput = this.state.newItemInput;
const newRadioValue = this.state.selectedValue;
const obj = {'item':newItemInput, 'columnType':newRadioValue};
const newArray = this.state.buyItems.slice(); // Create a copy
newArray.push(obj); // Push the object
this.setState({ buyItems: newArray });
console.log(this.state.buyItems);
}
how to push objects into array in ReactJS
change const x = Object.entries(book)
; to const x = Object.values(book);
How to push an object into an array with React Hooks
const buttonAddCategoryHandler = (e) => {
e.preventDefault()
const newArray = [...formElements.categories.cat, {value: 'newVal', displayValue: 'Friendly Value'}]
setFormElements({
...formElements,
categories: {
...formElements.categories,
cat: newArray
}
})
}
Append an object to an array, why does "push" not work?
You can't mutate a state directly in react. In your 2 cases:
const newToDo = [...todos, { text }];
This one creates a copy of the todos array and adds your extra item. newTodo is a copy and then when you setTodos(newTodo) you set the state to the new copied array.
const newToDo = todos.push({text})
This one tries to push {text} into todos which is a state. You can't mutate a state directly you have to do this through setTodos().
If you are really set on using push then you can copy the state of todos first then push into the copied array but I think this is extra unecessary work.
How to push Value in an array exist inside in an object of state in react
It sort of looks like you are using the current index to update state.
Shallow copy the state, and any nested state, that is being updated. Use the id
to match to the currently mapped comment state, and when you are on the comment you want to update, shallow copy the comment and update the replies
property by appending the reply
and returning a new array reference.
const addReply = (id, reply) => {
setComments(prevComments => prevComments.map(
(comment, index) => index === id
? {
...comment,
replies: comment.replies.concat(reply)
}
: comment
)
);
}
Ideally your comment
objects would have a GUID assigned to them, this way it's easier to match them independently of any array sorted order or any other issues that pop up when mutating arrays in React.
Example:
import { v4 as uuidV4 } from 'uuid';
...
const addComment = () => {
if (comment.desc !== "") {
setComments((prevComments) => {
return [...prevComments, { ...comment, id: uuidV4() }]
});
setComment({ author: "", desc: "", replies: [] });
setIsCommentVisible(true);
}
}
const addReply = (id, reply) => {
setComments(prevComments => prevComments.map(
(comment) => comment.id === id
? {
...comment,
replies: comment.replies.concat(reply)
}
: comment
)
);
}
Related Topics
How to Create a Remember Me Function in Login Without Using Form in JavaScript or Jquery
How to Stop Parsefloat() from Stripping Zeroes to Right of Decimal
Check If a String Is HTML or Not
How to Set Top and Bottom Margin in Addhtml
Button Enabled and Disabled Based on Checkbox Is Checked or Not
How to Reload Datatable by Ajax (Jquery)
Keep Order of Objects Inside a Json String After They Are Parsed
How to Reduce Vendor/Script Bundle.Js in Angular 5
Use Localstorage Across Subdomains
Making a JavaScript Function That Finds the First Word in a String/Sentence
Jquery Ui Tabs - How to Get Currently Selected Tab Index
Stop Chrome Back/Forward Two Finger Swipe
Combine Multiple JavaScript Files into One Js File
Angular 4 | Window.Scrollto(); Is Not Working Properly
How to Get the Id of a Button That Was Clicked - Reactjs
Angular - How to Get Result of a Json Object