Reputation: 1335
I do have a data set in the state of react native. I want to update some nested data and also append some data to the list of the object keys. For example:
const [data, setData] = useState({
set1: {current_page: 1, last_page: 2, data: [data1, data2, data3, data4]},
set2: {
current_page: 1,
last_page: 4,
data: [data11, data22, data33, data44],
},
set3: {
current_page: 1,
last_page: 5,
data: [data12, data22, data32, data42],
},
set4: {
current_page: 1,
last_page: 2,
data: [data11, data21, data31, data41],
},
});
This is my sample data type. Later I want to update only a single data key-value pair from the state like for the set2 key I want to set the current_page = 3 and last_page =5 and append the other few data to the data field from another list data. I don't want to affect any other data in the state. I want to update to:
let dataToAppend = [data55, data66, data77];
const [data, setData] = useState({
set1: {
current_page: 1,
last_page: 2,
data: [data1, data2, data3, data4],
},
set2: {
current_page: 3,
last_page: 5,
data: [data11, data22, data33, data44, data55, data66, data77],
},
set3: {
current_page: 1,
last_page: 5,
data: [data12, data22, data32, data42],
},
set4: {
current_page: 1,
last_page: 2,
data: [data11, data21, data31, data41],
},
});
Upvotes: 0
Views: 38
Reputation: 11156
You could always copy data
into a local variable, modify properties you need and set data
with new value. Something like:
let result = Object.assign({}, data); //<-- deep copy of data
result.set2.current_page = 17;
result.set2.last_page = 23;
result.set2.data.push(data43);
setData(result);
Upvotes: 0
Reputation: 529
You can use Spread operator:
setData({ ...data, set2: {...set2, current_page: 3, last_page: 5, data: [...set2.data, ...newItems]} })
Upvotes: 2