I hope you can help.
I can't remember where I got the the snippet of code in the deleteHandler function. It deletes the relevant listdata item from the JSON array and re-renders as expected. I just don't understand what it's doing. Is it specific React syntax? Is it rudimentary stuff that I am oblivious to?
I know the state.listdata.splice(id, 1); line gets the current JSON object, but what does the arrow function do? What is being returned? I'm quite baffled by it.
Any help is much appreciated.
var AppFront = React.createClass({
getInitialState:function(){
return{
listdata: [
{"id":1,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
{"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
}
},
deleteHandler: function(e,id){
this.setState(state => {
state.listdata.splice(id, 1);
return {listdata: state.listdata};
});
},
render: function(){
var listDataDOM = this.state.listdata.map((item,index) => {return (<li key={item.id}>
{item.name}
<button onClick={()=>this.deleteHandler(item.id)}>delete</button>
</li>)});
return(
<div>
<h1>To-do List</h1>
<ul>
{listDataDOM}
</ul>
</div>
);
}
});
ReactDOM.render(<AppFront />,document.getElementById("container"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
1) About setState
setState function in React looks something like that :
setState(partialState, callback)
Where partialState may be : object , function or null.
In your particular case you use function, which returns an object of state variables.
setState(function(state){ return {some:data} })
and with arrow func (es6) , the same will look like
setState(state=> { return {some:data} })
in yout particular case arrow func used just for short
2) About splice
In handler, you use JS func splice() to remove element from state's array;
But it is bad practice, because it mutates the state of component.And It will cause bugs, problems and unpredictable behavior. You shouldn't mutate your state!
To avoid that you can copy your array through slice(), because slice returns new array.
var newArray = state.listdata.slice()
newArray.splice(index, 1);
3) About deleteHandler and data structure
deleteHandler doesnt work properly, and works only for first position.And if your data will look like that:
listdata: [
{"id":52,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
{"id":11,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
It will not work at all
For proper result , you should change deleteHandler to this:
deleteHandler: function(e,id){
//find index of element
var index = this.state.listdata.findIndex(e=>e.id==id);
//copy array
var newAray = this.state.listdata.slice();
//delete element by index
newAray.splice(index, 1);
this.setState({listdata: newAray});
},
and button
<button onClick={e=>this.deleteHandler(e,item.id)}>delete</button>
> JSBIN example
or you can delete by index
deleteHandler: function(e,index){
//copy array
var newAray = this.state.listdata.slice();
//delete element by index
newAray.splice(index, 1);
this.setState({listdata: newAray});
},
<button onClick={e=>this.deleteHandler(e,index)}>delete</button>
> JSBIN example
In your AppFront component you have a state
{
listdata: [
{"id":1,"name":"Push Repo","description":"Job No 8790","priority":"Important"},
{"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
}
It represents initial data in your component. Every time you change state, your component gets rerendered.
You can change state by calling component's setState method
In deleteHandler
deleteHandler: function(e,id){
this.setState(state => {
// state.listdata - array of initial values,
state.listdata.splice(id, 1);
return {listdata: state.listdata}; // returns a new state
});
}
state.listdata.splice(id, 1) // removes an element with index == id from the array. You should not confuse listdata item.id and item index. In order for your code to work correctly you need to pass index in you deleteHandler.
<button onClick={()=>this.deleteHandler(index)}>delete</button>
Another thing is that you call deleteHandler only with one argument - item index so in your definition it should be
deleteHandler: function(index){
this.setState(state => {
// state.listdata - array of initial values,
state.listdata.splice(index, 1);
return {listdata: state.listdata}; // returns a new state
});
}
In your render method you iterate through this.state.listdata and return React.DOM nodes for each.
When you update component's state it gets rerendered and you see that item was deleted.
This code is written in es2015 so if it's new to you, it's better to start from reading something about new syntaxis.
state.listdata.splice(id, 1) deletes 1 element with the index equal to id from listdata array. For example if id equals to 0, then, after applying state.listdata.splice(id, 1), state.listdata will become:
listdata: [
{"id":2,"name":"Second Note","description":"Job No 823790","priority":"Important"}
]
And exactly this array will be returned by this arrow functions.
Keeping in mind, that splice method receives index as first argument, but you pass id property there, most probably you should change this code:
<button onClick={()=>this.deleteHandler(item.id)}>delete</button>
To:
<button onClick={()=>this.deleteHandler(index)}>delete</button>
Related
I have a filter options, which shows checkbox. So when click on each checkbox the value should be added to array if not exists and remove the value from array if already exists and the state should be updated. I have tried using below code and it is not working.
const [showFilter, setFilter] = useState([]);
useEffect(() => {
dispatch(fetchproducts(slug, sort, pageInitial+1, showFilter));
console.log(showFilter);
}, [showFilter]);
function filterClick (id, title) {
const index = showFilter.indexOf(id);
if (index > -1)
setFilter(showFilter.splice(index, 1));
else
setFilter(showFilter.concat(id));
}
return (
<ul style={{display: showMe.includes(index) ? "block" : "none"}}>
{item.items.map((single, index1) => (
<li key={index1}>
<label><input type="checkbox" name="checkbox" onClick={(e) => filterClick(e.target.value, item.title)} value={single.items_id}/> {single.items_value}</label>
</li>
))}
</ul>
)
In the above code, array insertion is working, but the splice is not working and the state is not updating.
How to alter my code to get the expected result.
You use useEffect. The useEffect's callback will be triggered when one of dependency is changed.
splice function changes array in place (ie mutates the array). In this case your array variable (showFilter) is not changed, therefore useEffect's callback will not be triggered.
Try using filter function instead:
setFilter(showFilter.filter(el=> el !== id));
Splice modifies the original array which is not considered a good practice in React. Please use slice or`filter.
Using slice your code would look like:
setFilter(showFilter.slice(index, index + 1))
I'm updating an object within react's state which I use to display a list. The state updates correctly, however the display breaks.
This is the section of the code from inside my render function which produces the list.
this.state.shoppingItems ? this.state.shoppingItems.currentShoppingItems.map((item, index) => {
console.log(item)
return <ItemSummary key={index} onClickHandler={this.selectItem} updateShoppingItem={this.updateCurrentShoppingItem} shoppingItem={item} removeFromCurrentItems={this.removeFromCurrentItems} addToCurrentList={this.addToCurrentList} />
}) : undefined}
Here is the code that produces the previous items list:
this.state.shoppingItems ? this.state.shoppingItems.previousShoppingItems.map((item, index) => {
console.log(item)
return <ItemSummary key={index} onClickHandler={this.selectItem} updateShoppingItem={this.updateCurrentShoppingItem} shoppingItem={item} removeFromCurrentItems={this.removeFromCurrentItems} addToCurrentList={this.addToCurrentList} />
}) : undefined}
This is the method which removes the item from the current list and adds it to the previous list, where the issue occurs.
removeFromCurrentItems(shoppingItem) {
const items = this.state.shoppingItems.currentShoppingItems.filter(item => item._id !== shoppingItem._id);
let shoppingItems = this.state.shoppingItems;
shoppingItems.currentShoppingItems = items;
shoppingItem.number = 0;
shoppingItem.completed = false;
shoppingItems.previousShoppingItems.push(shoppingItem);
this.setState({
shoppingItems: shoppingItems
});
// call to API to update in database
}
Here is the list before I remove the item.
Here is the list after I remove the middle item:
Finally here is the console.log output which shows that the items have updated properly but the display hasn't updated:
I'm entirely new to react coming from angular so I have no idea if this is the correct way to do this or if there is a better way. But could somebody help me figure out why the display isn't updating?
The issue seemed to be the key on the item in the map. I replaced the index with the item's id from the database as below and now it renders properly.
return <ItemSummary key={task._id} updateShoppingItem={this.updateCurrentShoppingItem} shoppingItem={task} removeFromCurrentItems={this.removeFromCurrentItems} addToCurrentList={this.addToCurrentList} />
Similar answer here:
Change to React State doesn't update display in functional component
The issue is the update for shoppingItems. You save a reference to the current state object, mutate it, and store it back in state. Spreading this.state.shoppingItems into a new object first will create a new object reference for react to pick up the change of.
React uses shallow object comparison of previous state and prop values to next state and prop values to compute what needs to be rerendered to the DOM and screen.
removeFromCurrentItems(shoppingItem) {
const items = this.state.shoppingItems.currentShoppingItems.filter(item => item._id !== shoppingItem._id);
const shoppingItems = {...this.state.shoppingItems};
shoppingItems.currentShoppingItems = items;
shoppingItem.number = 0;
shoppingItem.completed = false;
shoppingItems.previousShoppingItems.push(shoppingItem);
this.setState({
shoppingItems: shoppingItems
});
// call to API to update in database
}
I had a similar issue with my application in which I had to delete comments made.
<textarea disabled key={note._id} className="form-control">{note.note}</textarea>
But the issue got resolved when I added the Key attribute to the list item.
this.state = {
myArray = [
{
name:"cat",
expand:false
}
]
}
clickItem(item){
item.expand = true;
this.setState({})
}
this.state.myArray.map((item) =>{
return <div onClick={()=>this.clickItem(item)}>{item.name}</div>
})
In React, i have a simple array of objects,
when i click on one of theses object, i want to change their prop and update the state, what is the proper way of doing this.
i feel like there could be a better way
You need to copy your state, update the copied state and the set the state.
this.state = {
myArray = [
{
name:"cat",
expand:false
}
]
}
clickItem(key){
let items = this.state.myArray;
items[key].expand = true;
this.setState({items})
}
this.state.myArray.map((key, item) =>{
return <div onClick={()=>this.clickItem(key)}>{item.name}</div>
})
Okay, a couple of things.
You're mutating the state directly which is going to fail silently and you're also missing the key prop on your <div.
This is easily resolved though by using the data you have available to you. I don't know whether each name is unique but you can use that as your key. This helps React decide which DOM elements to actually update when state changes.
To update your item in state, you need a way to find it within the state originally, so if name is unique, you can use Array.prototype.find to update it.
clickItem(item) {
const targetIndex = this.state.items.find(stateItem => stateItem.name === item.name)
if (targetIndex === -1)
// Handle not finding the element
const target = this.state.items[targetIndex]
target.expand = !target.expand // Toggle instead of setting so double clicking works as expected.
this.setState({
items: this.state.items.splice(targetIndex, 1, target) // This replaces 1 item in the target array with the new one.
})
}
This will update state and re-render your app. The code is untested but it should work.
I'm making a primitive quiz app with 3 questions so far, all true or false. In my handleContinue method there is a call to push the users input from a radio form into the userAnswers array. It works fine for the first run of handleContinue, after that it throws an error: Uncaught TypeError: this.state.userAnswers.push is not a function(…)
import React from "react"
export default class Questions extends React.Component {
constructor(props) {
super(props)
this.state = {
questionNumber: 1,
userAnswers: [],
value: ''
}
this.handleContinue = this.handleContinue.bind(this)
this.handleChange = this.handleChange.bind(this)
}
//when Continue button is clicked
handleContinue() {
this.setState({
//this push function throws error on 2nd go round
userAnswers: this.state.userAnswers.push(this.state.value),
questionNumber: this.state.questionNumber + 1
//callback function for synchronicity
}, () => {
if (this.state.questionNumber > 3) {
this.props.changeHeader(this.state.userAnswers.toString())
this.props.unMount()
} else {
this.props.changeHeader("Question " + this.state.questionNumber)
}
})
console.log(this.state.userAnswers)
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
render() {
const questions = [
"Blargh?",
"blah blah blah?",
"how many dogs?"
]
return (
<div class="container-fluid text-center">
<h1>{questions[this.state.questionNumber - 1]}</h1>
<div class="radio">
<label class="radio-inline">
<input type="radio" class="form-control" name="trueFalse" value="true"
onChange={this.handleChange}/>True
</label><br/><br/>
<label class="radio-inline">
<input type="radio" class="form-control" name="trueFalse" value="false"
onChange={this.handleChange}/>False
</label>
<hr/>
<button type="button" class="btn btn-primary"
onClick={this.handleContinue}>Continue</button>
</div>
</div>
)
}
}
Do not modify state directly! In general, try to avoid mutation.
Array.prototype.push() mutates the array in-place. So essentially, when you push to an array inside setState, you mutate the original state by using push. And since push returns the new array length instead of the actual array, you're setting this.state.userAnswers to a numerical value, and this is why you're getting Uncaught TypeError: this.state.userAnswers.push is not a function(…) on the second run, because you can't push to a number.
You need to use Array.prototype.concat() instead. It doesn't mutate the original array, and returns a new array with the new concatenated elements. This is what you want to do inside setState. Your code should look something like this:
this.setState({
userAnswers: this.state.userAnswers.concat(this.state.value),
questionNumber: this.state.questionNumber + 1
}
Array.push does not returns the new array. try using
this.state.userAnswers.concat([this.state.value])
this will return new userAnswers array
References: array push and array concat
You should treat the state object as immutable, however you need to re-create the array so its pointing to a new object, set the new item, then reset the state.
handleContinue() {
var newState = this.state.userAnswers.slice();
newState.push(this.state.value);
this.setState({
//this push function throws error on 2nd go round
userAnswers: newState,
questionNumber: this.state.questionNumber + 1
//callback function for synchronicity
}, () => {
if (this.state.questionNumber > 3) {
this.props.changeHeader(this.state.userAnswers.toString())
this.props.unMount()
} else {
this.props.changeHeader("Question " + this.state.questionNumber)
}
})
console.log(this.state.userAnswers)
}
Another alternative to the above solution is to use .concat(), since its returns a new array itself. Its equivalent to creating a new variable but is a much shorter code.
this.setState({
userAnswers: this.state.userAnswers.concat(this.state.value),
questionNumber: this.state.questionNumber + 1
}
The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:
this.setState(prevState => ({
userAnswers: [...prevState.userAnswers, this.state.value]
}));
I have found a solution. This shoud work for splice and others too. Lets say that I have a state which is an array of cars:
this.state = {
cars: ['BMW','AUDI','mercedes']
};
this.addState = this.addState.bind(this);
Now, addState is the methnod that i will use to add new items to my array. This should look like this:
addState(){
let arr = this.state.cars;
arr.push('skoda');
this.setState({cars: arr});
}
I have found this solution thanks to duwalanise. All I had to do was to return the new array in order to push new items. I was facing this kind of issue for a lot of time. I will try more functions to see if it really works for all functions that normally won't. If anyone have a better idea how to achieve this with a cleaner code, please feel free to reply to my post.
The correct way to mutate your state when you want to push something to it is to do the following. Let's say we have defined a state as such:
const [state, setState] = useState([])
Now we want to push the following object into the state array. We use the concat method to achieve this operation as such:
let object = {a: '1', b:'2', c:'3'}
Now to push this object into the state array, you do the following:
setState(state => state.concat(object))
You will see that your state is populated with the object.
The reason why concat works but push doesn't is because of the following
Array.prototype.push() adds an element into original array and returns an integer which is its new array length.
Array.prototype.concat() returns a new array with concatenated element without even touching in original array. It's a shallow copy.
I trying trying to achieve the following: There is a textfield and once a user enters in a text, an object is created with the text assigned to a state property called 'commentText' which is located inside the 'comments' array which is inside the object (todo[0]) of 'todos' array. 'commentInput' is just a temporary storage for the input entered in the textfield, to be assigned to the 'commentText' of 'todo[0]' object's 'comments' array.
I retrieve the current state object via following:
const mapStateToProps=(state, ownProps)=>({
todo:state.todos.filter(todo=>todo.id==ownProps.params.id)
});
and dispatch and actions via:
function mapDispatchToProps(dispatch){
return{
actions: bindActionCreators(actions, dispatch)
}
So the retrieved object 'todo' has an array property named comments. I have a text field that has:
onChange={this.handleCommentChange.bind(this)}
which does:
handleCommentChange(event){
this.props.actions.updateComment(event.target.value)
}
Before handleCommentChange is called, the object 'todo[0]' is first fetched correctly:
But as soon as a text is inputted into the text field, onChange={this.handleCommentChange.bind(this)} is called and all of a sudden, 'todo[0]' state is all lost (as shown in the 'next state' log):
What may be the issue? Tried solving it for hours and hours but still stuck. Any guidance or insight would be greatly appreciated. Thank you in advance.
EDIT **:
{
this.props.newCommentsArray.map((comment) => {
return <Comment key={comment.id} comment={comment} actions={this.props.actions}/>
})
}
EDIT 2 **
case 'ADD_COMMENT':
return todos.map(function(todo){
//Find the current object to apply the action to
if(todo.id === action.id){
//Create a new array, with newly assigned object
return var newComments = todo.comments.concat({
id: action.id,
commentTxt: action.commentTxt
})
}
//Otherwise return the original array
return todo.comments
})
I would suspect that your reducer is not correctly updating the todo entry. It's probably replacing the contents of the entry entirely, rather than merging the incoming value in in some fashion.
edit:
Yup, after seeing your full code, your reducer is very much at fault. Here's the current code:
case 'ADD_COMMENT':
return todos.map(function(todo){
if(todo.id === action.id){
return todo.comments = [{
id: action.id,
commentTxt: action.commentTxt
}, ...todo.comments]
}
})
map() should be returning one item for every item in the array. Instead, you're only returning something if the ID matches, and even then, you're actually assigning to todo.comments (causing direct mutation) and returning the result of that statement (which might be undefined?).
You need something like this instead (which could be written shorter, but I've deliberately written it out long-form to clarify what's happening):
case 'ADD_COMMENT':
return todos.map(function(todo) {
if(todo.id !== action.id) {
// if the ID doesn't match, just return the existing objecct
return todo;
}
// Otherwise, we need to return an updated value:
// Create a new comments array with the new comment at the end. concat() will
// You could also do something like [newComment].concat(todo.comments) to produce
// a new array with the new comment first depending on how you want it ordered.
var newComments = todo.comments.concat({
id : action.id,
commentTxt : action.commentTxt
});
// Create a new todo object that is a copy of the original,
// but with a new value in the "comments" field
var newTodo = Object.assign({}, todo, {comments : newComments});
// Now return that instead
return newTodo;
});