Reputation: 141
I have tried to change the value of DataContext
so i tried like this:
const changeSecondLabel = index => value => {
setDataContext(dataContext =>
dataContext.map((data, i) =>
i === index
? {
...data,
datasets: [{ ...data.datasets.label, label: value }],
}
: data
)
);
};
DataContext
const [DataContext, setDataContext] = useState([
{
labels: defaultLabels,
datasets: [
{
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
}, ///
{
labels: defaultLabels,
datasets: [
{
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
}, ///
{
labels: defaultLabels,
datasets: [
{
label: "dataSetting",
data: defaultDatas,
backgroundColor: defaultBackgroundColor,
},
],
}, ///....
However, whenever I change the label
to value. then, the DataContext
datasets
is disappeared .
I assume that deep copying datasets
is not the way i should do ,
So i want to know how to fix it .
Thank you in advance !
Upvotes: 0
Views: 42
Reputation: 4633
I tried to replicate the code structure you have provided and came up with a solution. You cannot directly apply the rest operator to the dataset since it is an array and you are planning to apply the rest operator to each elements inside the dataset.
Hence,I mapped the datasets
and applied the deep level rest operator.
let dataSet = [
{
labels: "One",
datasets: [
{
label: "dataSetting",
data: "defaultDatas",
backgroundColor: "defaultBackgroundColor",
},
],
},{
labels: "Two",
datasets: [
{
label: "TwodataSetting",
data: "TwodefaultDatas",
backgroundColor: "TwodefaultBackgroundColor",
},
],
},{
labels: "Three",
datasets: [
{
label: "ThreedataSetting",
data: "ThreedefaultDatas",
backgroundColor: "ThreedefaultBackgroundColor",
},
],
},
];
const changeSecondLabel = index => value => {
debugger;
dataSet = dataSet.map((data, i) =>
i === index
? {
...data,
datasets: data.datasets.map(set => {return {...set, label: value}}),
}
: data
)
};
changeSecondLabel(1)("New Value");
console.log(dataSet);
Upvotes: 2