Goal: Update local form state using computed property names.
Problem: The computed property name does not overwrite/update my state. Instead it makes multiple copies
What it currently does: New objects get added to my array
const [channelOptions, setChannelOptions] = useState([
{ eml: false },
{ push: false },
{ inapp: false }
]);
Handler to update state when checkbox element is selected
const channelSelectionChangeHandler = (e) => {
setChannelOptions((prevState) => {
return [...prevState, { [e.target.value]: e.target.checked }];
});
};
Outcome - Multiple copies of inapp. The goal was to overwrite it
0:{eml: false}
1:{push: false}
2:{inapp: false}
3:{inapp: true}
4:{inapp: false}
5:{inapp: true}
What am I doing wrong? I think this is down to referencing.
Thanks!
If possible I will use an Object like { eml: false, push: false, inappropriate: false } instead of an array of objects.
Then I set new state with setChannelOptions(prev => ({...prev, [e.target.value]: e.target.checked }))
If you DO need to use array of objects, you can do it like this.
setChannelOptions( prevState => prevState.map( x => x[e.target.value] !== undefined ? { e.target.value: e.target.checked } : x )
});
What we do here is to .map through the array, check if the key exists (is defined). If the key exists, update with new value, else return the original object.
Related
I am on the newer side of React and trying to change the state of an object in an array. Currently, I am pulling the object out of the array, changing the property in that object, then adding the new object to the state again. Problem being that it sends the object to the back of the list and reorders my checkbox inputs.
const handleChange = (e) => {
if (e.target.type === "checkbox") {
// Get the role from the current state
const roleToChange = input.roles.find(
(role) => Number(role.id) === Number(e.target.id)
);
// Change checked state to opposite of current state
const changedRole = { ...roleToChange, checked: !roleToChange.checked };
// Get every role except the one that was changed
const newRoles = input.roles.filter(
(role) => Number(role.id) !== Number(e.target.id)
);
// Update the role in the state
setInput((prevState) => {
return { ...prevState, roles: [...newRoles, changedRole] };
});
}
Can I update the object in the array in-place so this doesn't happen?
Don't .filter - .map instead, and return the changed object in case the ID matches, so the new object gets put at the same place in the new array as it was originally.
const handleChange = (e) => {
if (e.target.type !== "checkbox") {
return;
};
const newRoles = input.roles.map((role) =>
Number(role.id) !== Number(e.target.id)
? role
: { ...role, checked: !role.checked }
);
setInput((prevState) => {
return {
...prevState,
roles: newRoles
};
});
}
Unless the state is updated synchronously before this, which sounds a bit unlikely (but not impossible), you can also probably use setInput({ ...input, roles: newRules }) instead of the callback.
I have a multitabbed view that I am controlling the data with through a global state, being passed through useContext (along with the setState updater function).
The structure is similar to
globalState: {
company: {
list: [
[{name: ..., ...}, {field1: ..., ... }],
[{name: ..., ...}, {field1: ..., ... }],
...
]
},
...
}
I have a table in this first tab, where each row that displays the details in the first object of each inner list array (globalState.company.list[X][0]), and has a few checkboxes to toggle fields in the second object in each inner list array (globalState.company.list[X][1]).
The issue I am having is that when I check a checkbox for a specific field, all companies have that field set to that value before I call setGlobalState(...) in that onChange call from the checkbox itself.
Here is all the related code for the flow of creating the checkbox and the handler:
<td><Checkbox
disabled={tpr.disabled} // true or false
checked={tpr.checked} // true or false
onChange={checkboxOnChange} // function handler
targetId={company.id} // number
field={"field1"} />
</td>
Checkbox definition
const Checkbox = React.memo(({ disabled, checked, onChange, targetId, field }) => {
return (
<input
type="checkbox"
style={ /* omitted */ }
defaultChecked={checked}
disabled={disabled}
onChange={(e) => onChange(e, targetId, field)}
/>
);
});
onChange Handler callback
const checkboxOnChange = (e, id, field) => {
const checked = e.target.checked;
console.log("GLOBAL STATE PRE", globalState.companies.list);
let foundCompany = globalState.companies.list.find(company => company[0].id === id);
foundCompany[1][field].checked = checked;
console.log("foundCompany", foundCompany);
console.log("GLOBAL STATE POST", globalState.companies.list);
setGlobalState(prevState => ({
...prevState,
companies: {
...prevState.companies,
list: prevState.companies.list.map(company => {
console.log("company PRE ANYTHING", company);
if (company[0].id === foundCompany[0].id) {
console.log("Inside here");
return foundCompany;
}
console.log("company", company);
return company;
})
}
}));
};
I see from the GLOBAL STATE PRE log that if I were to check a box for field1, then all companies would have field1 checked well before I modify anything else. I can confirm that before the box is checked, the globalState is as I expect it to be with all of the data and fields correctly set on load.
In the picture below, I checked the box for TPR in the second company array, and before anything else happens, the second and third companies already have the TPR set to true.
Any help would be appreciated, and I will share any more details I am able to share. Thank you.
Just don't mutate the state object directly:
const checkboxOnChange = (e, id, field) => {
const checked = e.target.checked;
setGlobalState(prevState => ({
...prevState,
companies: {
...prevState.companies,
list: prevState.companies.list.map(company => {
if (company[0].id === id) {
return {
...company,
checked
};
}
return {
...company
};
})
}
}));
};
The globalState object is being updated before you call setGlobalState because you are mutating the current state (e.g. foundCompany[1][field].checked = checked;)
One way of getting around this issue is to make a copy of the state object so that it does not refer to the current state. e.g.
var cloneDeep = require('lodash.clonedeep');
...
let clonedGlobalState = cloneDeep(globalState);
let foundCompany = clonedGlobalState.companies.list.find(company => company[0].id === id);
foundCompany[1][field].checked = checked;
I recommend using a deep clone function like Lodash's cloneDeep as using the spread operator to create a copy in your instance will create a shallow copy of the objects within your list array.
Once you have cloned the state you can safely update it to your new desired state (i.e. without worry of mutating the existing globalState object) and then refer to it when calling setGlobalState.
Goal :
Within a React App, understand how to correctly update a boolean value that is stored within an array in state.
Question :
I am not sure if my code is correct in order to avoid asynchronous errors (whether or not it works in this case I am not interested in as my goal is to understand how to avoid those errors in all cases). Is there some syntax that is missing in order to correctly create a new state?
Context :
Creating a todo list within React.
My state consists of an array labeled itemsArr with each array element being an object
The objects initialize with the following format :
{ complete : false, item : "user entered string", id : uuid(), }
Upon clicking a line item, I am calling a function handleComplete in order to strikethrough the text of that line by toggling complete : false/true
The function is updating state via this :
handleComplete(id){
this.setState(state =>
state.itemsArr.map(obj => obj.id === id ? obj.complete = !obj.complete : '')
)
}
Additional Details :
One of my attempts (does not work) :
handleComplete(id){
const newItemsArr = this.state.itemsArr.map(obj =>
obj.id === id ? obj.complete = !obj.complete : obj);
this.setState({ itemsArr : newItemsArr })
}
In both snippets you haven't correctly returned a new object from the .map callback:
handleComplete(id){
const newItemsArr = this.state.itemsArr.map(obj =>
obj.id === id ? { id: obj.id, complete: !obj.complete } : obj);
this.setState({ itemsArr : newItemsArr });
}
Your function, as mentioned above, returns and updates wrong data, by adding new elements in your state instead of updating your current array.
Since array.map() returns an array, you can assign it to the state array, itemsArr.
You should also replace the change condition by updating the element's value first, and then returning it, if its id matches,or else, simply leave it as is.
handleComplete=(id)=>{
this.setState(state =>{
itemsArr:state.itemsArr.map(obj => obj.id === id
? (obj.complete = !obj.complete,obj) //update element's complete status and then return it
: obj) //return element as is
},()=>console.log(this.state.itemsArr)) //check new state
}
live example using your data : https://codepen.io/Kalovelo/pen/KKwyMGe
Hope it helps!
state = {
itemsArr: [
{
complete: false,
item: 'iemName',
id: 1
},
{
complete: false,
item: 'iemName',
id: 2
}
]
}
handleComplete = (id) => {
let { itemsArr } = { ...this.state };
itemIndex = itemsArr.findIndex(item => id === item.id);
itemsArr[itemIndex]['complete'] = !itemsArr[itemIndex]['complete'];
this.setState{itemsArr}
}
I am confused about executing spread operator and using it to update state array like that
todos: [
{
id: "1",
description: "Run",
completed: "true"
},
{
id: "2",
description: "Pick John",
completed: "false"
}]
I have objects inside my array, the examples provided after searching are using spread operator to update arrays with single object, how can I update that object with "id" that equals "key" only. My wrong function is
markTaskCompleted(e) {
var key = e._targetInst.key;
this.setState(
{
todoList: // state.todoList is todos variable
[...this.state.todoList, this.state.todoList.map(task => {
if (task.id == key) task.completed = "true";
}) ]
},
this.getTodos
);
}
The result of this array is the same array of todos (spread operator) with array of undefined items.
I have been googling for some time but couldn't really get it.
Instead of destructuring the array and using map, I typically update a single item's value with a single map that replaces the item I am updating and returns the existing value for all other items. Something like this:
this.setState((prevState) => {
return {
todoList: prevState.todoList.map((task) => {
if (task.id === key) {
return { ...task, completed: true };
} else {
return task;
}
}),
};
});
Also, notice that this example passes a function to this.setState rather than an object. If you are updating the state based on the previous state (in this example using todoList from the previous state) you should use the function method. setState is asynchronous and you could get unexpected results from using this.state to compute the new state.
I have this Object.key code that pushes all items:
const cloned_items = [];
Object.keys(items).sort().map(key => {
let item = {
[`item-${uid}`]: {
item: false
}
}
cloned_items.push({ ...item });
});
database.ref('/app/items').update({
...cloned_items
})
but this produces following result:
"0" : {
"timeslot-87dah2j" : {
item: false
}
},
"1" : {
"timeslot-7s1ahju" : {
item: false
}
}
instead of:
"timeslot-87dah2j" : {
item: false
},
"timeslot-7s1ahju" : {
item: false
}
any idea ?
It seems like you want to create a plain object, not an array.
In that case:
const cloned_items = Object.assign(...Object.keys(items).map(uid =>
({ [`item-${uid}`]: {item: false} })
));
NB: sorting is of no use when creating an object -- its keys are supposed to have no specific order.
You're creating an array of objects. Seems like you want to use .reduce() to create a single object from the array.
const cloned_items = Object.keys(items).sort().reduce((obj, key) =>
Object.assign(obj, { [`item-${uid}`]: { item: false } })
, {});
Your code doesn't show where uid is coming from, but I assume you meant key there, along with timeslot instead of item.
You may find Object.defineProperty to be cleaner, though you'll need to set up the property descriptor as you want it.
const cloned_items = Object.keys(items).sort().reduce((obj, key) =>
Object.defineProperty(obj, `item-${uid}`, {value:{item: false}})
, {});