React setState to array element - reactjs

I want to update list with React.
List I have:
export const arrList = [
{ title: '', elements: [] },
{ title: 'a', elements: ['aaa', ] },
{ title: 'b', elements: ['bbb', ] },
];
const [poreikiai, setPoreikiai] = useState(arrList);
And now, I want to append to first array element: elements { title: '', elements: [] }
I something like this:
{ title: '', elements: ["firstElement"] }
how can I do it?
I understant that I need to use setPoreikiai but I cant figure out sintax;
Something like:
setPoreikiai(prevState => {
return {...prevState, ...newValue};
});```

Deeply clone your way into the data structure and add the new item at the end:
setPoreikiai(prevState => {
const prevClone = [...prevState];
prevClone[0] = {
...prevClone[0],
elements: [...prevClone[0].elements, "secondItem"]
};
return prevClone;
});
It's important that you create copies all the way down to the desired level of state so that you do not accidently mutate any values by reference. Any directly mutated data can become out of sync with other effects and memoised components which might accept them as dependencies.

Related

React: check if a data is duplicated in a map to ignore it

Is there any way to know if a data is repeated within a map? For example:
newArray = [name: "Jose", name:"Pedro", name:"Jose", name:"Ramon"]
newArray.map((questmapn: any, index: any) => ({questmapn.name}))
I need to know if questmapn.name is repeated inside the loop to create a ternary that doesn't show the duplicates. Is there a simplified way?
You can use onlyUnique function like below:
const newArray = [
{ name: "Jose" },
{ name: "Pedro" },
{ name: "Jose" },
{ name: "Ramon" }
];
function onlyUnique(repeatedArray) {
const names = [];
const uniqueArray = [];
repeatedArray.forEach((item) => {
if (!names.includes(item.name)) {
names.push(item.name);
uniqueArray.push(item);
}
});
return uniqueArray;
}
const uniqueArray = onlyUnique(newArray);
Note: Pass repeated array to this function and returned value will be unique based on name property.

Update value in nested object using React Hooks

My desire is to update the products inside the shoppingCart[0]
The state: const [authenticatedUser, setAuthenticatedUser] = useContext<any>(UserContext)
console.log(authenticatedUser) displays the following:
I've tried updating the value of the products array with the following code:
setAuthenticatedUser({ ...authenticatedUser, products: ['new item'] })
But it creates a new product array inside the authenticatedUser.
How can I update the products array inside authenticatedUser.shoppingCart[0].products ?
Data:
const [authenticatedUser, setAuthenticatedUser] = useState(
{
authenticated: true,
id: "3i4jijrifjifrjifr",
shoppingCart: [{
createdAt: "2021-01-29T10:14:21.253Z",
products: ['this is the array i want to update', '2', '3']
}]
}
)
try this:
setAuthenticatedUser({ ...authenticatedUser, shoppingCart:[{...authenticatedUser.shoppingCart[0],products:['newItem']}] })
const authenticatedUserCopy = { ...authenticatedUser }
authenticatedUserCopy.shoppingCart[0].products = ['new product']
setAuthenticatedUser(authenticatedUserCopy)
{
...authenticatedUser,
shoppingCart: authenticatedUser.shoppingCart.map(s => { //map all items
return {
...s,
products: [...s.products, 'new item'] //add item
}
})
}

How to add properties to an object that is inside an array of objects with useState hook

I have an array of objects created from useState hook:
const [arrayOfObjects, setArrayOfObjects] = useState([]);
setArrayOfObjects([{id:1}, {id:2}, {id:3}]);
How do I add a property to each object through the setArrayOfObjects function so that it will be:
[
{
id:1,
name: "one",
},
{
id:2,
name: 'two',
},
{
id:3,
name: 'three',
},
]
Thanks!
for that you can use the map operator in the array type. That will return a new array with your data transformed (mapped) to something else like this:
let newarrayOfObjects = arrayOfObjects.map(e => {
return {
id: e.id,
name: someVariableWithTheName,
}
});
setArrayOfObjects(newarrayOfObjects);
if you need the index of the element to do something the map method actually takes two arguments, first the element and second the index of the element so code can be use as this:
let newarrayOfObjects = arrayOfObjects.map(e, index => {
return {
id: e.id,
name: index,
}
});
setArrayOfObjects(newarrayOfObjects);
Define the array to add and use JavaScript array map function.
const additionalArr = [{name: 'one'}, {name: 'two'}, {name: 'three'}];
const newArrayOfObjects = arrayOfObjects.map((obj, idx) => ({
...obj,
...additionalArr[idx]
}));
setArrayOfObjects(newArrayOfObjects);

Adding to an array within an array state in ReactJS

I'm trying to add functionality for adding to a state, more specifically "list", in the following state:
shoeList : [
{name: 'Nike',
list : [
{type: 'boots', revenue: '1000000', gender: 'mens', price: '49.99', id: 3},
{type: 'shoes', revenue: '13280100', gender: 'womens', price: '99.99', id: 2}
]
}
],
Right now I have a component that displays a form for the user to enter new values for type revenue gender and price.
Here is the code for the component(not including the forms and text input html):
state = {
}
//when changes occur in text input fields
handleChange = (e) => {
this.setState({
[e.target.id]: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault();
this.props.addShoe(this.state);
And in the root component i have the addShoe function:
addShoe = (shoe) => {
shoe.list.id = Math.random();
//returns a new array so no alteration of original array
let shoeList = [...this.state.shoeList, shoe];
this.setState({
shoeList: shoeList
})
}
Trying this code gives me an error saying shoe.list.id is undefined? Also I think I'm missing something to add in the component file specifically in the state. Also is there any way to directly access list like this.state.shoeList.list? I'm not sure if i have to add list to shoeList. Any help would be great thanks
In your example, if the intention is to add an item to specifically the Nike list:
addShoe = (shoe) => {
this.setState({
// return an altered copy of the array via map
shoeList: this.state.shoeList.map(brandItem => {
if (brandItem.name === 'Nike') {
return {
// use spread syntax for other object properties to persist
...brandItem,
list: [
// use spread syntax to keep the original items in the list
...brandItem.list,
{
// assuming shoe is an object without an id property
...shoe,
id: Math.random()
}
]
}
} else {
return brandItem;
}
})
}

How can I update a nested state with arrays in React?

I have a nested array, and I am trying to update some properties, but i don't know the syntax in react to do that.
this.state = {
databasesList: {
name: 'Databases',
toggled: true,
children: [
{
name: 'OneDatabase',
children: [
{ name: 'collection1' },
{ name: 'collection2' }
]
}
]
}
}
I am trying to update with this, but it does not work:
this.setState({ this.state.databasesList.children[0].children: newData })
To set nested state in React you should use JS spread operator so in your example it should be something like this:
this.setState((prevState) => ({
...prevState,
databasesList: {
...prevState.databasesList,
children: {
...prevState.databasesList.children[0],
children: {
newData,
},
},
},
}));
If you want to use lodash set here's a pretty nifty solution.
https://twitter.com/stwilz/status/1092958989208317952
But if you just want to use set on it's own this would be the way to go.
const yourFunction = newData => this.setState(state => set(state, ['databasesList', 'children', 0, 'children'], newData));
The spread operator works fine as well. It just gets super verbose when you have a huge state object.

Resources