score:5
am i not following best practices here?
nope. the problem is that you are not working with temporary variables, like you might believe, but are mutating deleteditems
directly. basically:
const itemsstate = this.state.items;
const deleteditemsstate = this.state.deleteditems;
these lines do not create a copy of the respective state variables, but instead only creates a reference to them.
so when you do
deleteditemsstate.push(itemtobedeleted);
you are mutating the state directly! which is a no-no, as you probably already know.
why does this happen?
to understand this, you must understand that assignments between primitive and compound values work differently.
for example:
var x = y;
x
will copy the value of y
if y
is a string, number, boolean, null or undefined. however, if it's an object, array or a function x
will store its reference.
solution:
what you need to do is to create a shallow copy of them. like so:
const itemsstate = this.state.items.slice();
const deleteditemsstate = this.state.deleteditems.slice();
this will make itemsstate
and deleteditemsstate
separate variables from this.state.item
and this.state.deleteditems
respectively.
demo:
class myapp extends react.component {
constructor() {
super();
this.state = {
items: ['item 1', 'item 2', 'item 3'],
deleteditems: ['item 4', 'item 5']
};
}
removeitem = (number) => {
const itemsstate = this.state.items;
const deleteditemsstate = this.state.deleteditems;
const itemtobedeleted = itemsstate[number];
deleteditemsstate.push(itemtobedeleted);
itemsstate.splice(number, 1);
this.setstate({
items: itemsstate
}, () => {
console.log(this.state);
});
}
render() {
return (
<div>
items:
<ul>
{this.state.items.map((item, i) => <li>{item} <button onclick={this.removeitem.bind(this, i)}>remove</button></li>)}
</ul>
deleted items:
<ul>
{this.state.deleteditems.map(item => <li>{item}</li>)}
</ul>
</div>
);
}
}
reactdom.render( < myapp / > , document.getelementbyid("app"));
<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>
<div id="app"></div>
score:0
this is not the correct way to handle state changes in your app.
for instance, this line
const itemsstate = this.state.items;
it creates a variable itemsstate which points to this.state.items. so any changes you make to itemsstate, it will get changed in your state.items as well. this mutates your data.
the best practice is to use a library such as immutability-helper to make state updates or either clone your state object into variables and then perform mutations on them. and after you are done, finally update the state using setstate().
here is a code snippet to explain how you can clone using object.assign(). this won't change your original state variables as you can see in the snippet.
var state = {
items: ['item 1', 'item 2', 'item 3'],
deleteditems: ['item 4', 'item 5']
};
function removeitem(number) {
const itemsstate = object.assign([], this.state.items);
const deleteditemsstate = object.assign([], this.state.deleteditems);
const itemtobedeleted = itemsstate[number];
deleteditemsstate.push(itemtobedeleted);
itemsstate.splice(number, 1);
//this.setstate({ items: itemsstate });
console.log(state);
}
removeitem(1);
Source: stackoverflow.com
Related Query
- React state variable updates automatically without calling setState
- React state is updating without calling setState
- react js state variable updates automatically without setstate method
- React state updates without me calling setState?
- React state updates without a setState function - Unexpected
- Why does calling react setState method not mutate the state immediately?
- Calling setState in a loop only updates state 1 time
- How to test React state after calling a component method that updates state - using Enzyme
- How to know if all the setState updates have been applied to the state in a React component?
- Mutating state on React manually, then calling setState
- why state updating itself? Without calling setState
- React Asynchronous State Updates setState argument (function vs non-function)
- React push to state variable without setState
- React : why state change when try to change it in immutable way , before calling the setState
- React state array object changes without setState
- React change state from another component without passing setState method
- UseState updates in react without calling set function
- Can you force a React component to rerender without calling setState?
- React setState not updating state
- allow typescript compiler to call setState on only one react state property
- Why calling setState method doesn't mutate the state immediately?
- When testing, code that causes React state updates should be wrapped into act
- How to update react state without re-rendering component?
- init state without constructor in react
- React.js without JSX - "Warning: Something is calling a React component directly. Use a factory or JSX instead"
- How to correctly set initial state in React with Typescript without constructor?
- TypeScript React State without Props
- React Hooks: accessing state across functions without changing event handler function references
- How do I avoid unused setState functions? Can React useState be created without a setter?
- React - Changing the state without using setState: Must avoid it?
More Query from same tag
- Unexpected token 'react' when using react-moralis
- Nested route request interpreted as request for CSS file
- how do refactoring one types expression in typescript and react project
- Want to send JWT token in headers along with data using axios but getting this error : Cannot set headers after they are sent to the client
- Fibonacci Counter in React.js
- How to keep semantic-ui modal from closing when displaying different components?
- Not able to set background image through react component, getting error
- React: [useRef, scrollIntoView,] How to only autoscroll a specific div inside of an overflowing page?
- How to navigate to the update/detail page after a POST in RTK query
- Material UI paper with dynamic height and width
- Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). Nextjs + firebase
- react-router - pass props to handler component
- useState not reflecting changes
- React Table: Filtering specific columns within a Global Filter
- React - Change component by the router
- TableHeader of Material UI does not make the content bold
- ./activetenant' does not contain an export named 'ActiveTenant'
- if/else statements inside a function for react-table
- how to get input field values in react?
- How to set property of a React component in its constructor
- Temporarily upload on S3 and remove if it's not used?
- How to customize css borders like google?
- MUI DataGrid custom cells and space button
- How to transpile and minify single file with webpack?
- How can I lock the zoom level in a Leaflet map?
- 'This' is undefined when click event method is launched
- Can I change toolbar language in grapesjs?
- "Cannot read property 'type' of undefined" in redux store for action defined in external package
- toggle between multiple button style on click of button in react
- React object property setting broken