Shubham Khatri Shubham Khatri - 1 month ago 7
React JSX Question

Append data to the nested redux store

I am working on creating a

Line chart
in
react-chartjs
, for that I am fetching data from an API at regular interval and and on success I am dispatching an action that updates the
reducer-state
. I have an initial data in my redux store as

var lagData = [{
options: {
responsive: true,
legend: {
position: 'top'
},
title: {
display: true,
text: 'ETL lag in minutes'
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}],
yAxes: [{
stacked: true
}]
}
},
data: {
labels: [],
datasets: [
{
label: 'Current lag',
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
spanGaps: false,
data: []
}
]
}
}]


In this store I am trying to append data to the
label
and
data
tags. But I can't figure out how, I am trying it as follows but it doesn't work

const lagInfo = (state = lagData, action) => {
switch(action.type) {
case 'GET_CURRENT_LAG_RECEIVED':
console.log(action.data);
return Object.assign({}, state, {
data: Object.assign({}, state.data.datasets.data, {
x: "afsa",
y: "fa"
})
});
break;
case 'GET_CURRENT_LAG_ERROR':
console.log(action.err);
return action.err;
break;
default:
return state;

}
}

export default lagInfo;


Any help is appreciated

Answer

You can use immutability-helper to update state in an immutable way. The code should look like:

import update from 'immutability-helper'; //import helper
// ....
case 'GET_CURRENT_LAG_RECEIVED': 
  return update(state, {
    0: {
      data: {
         datasets: {
           0: {
              data: {$push: [{ x: "afsa", y: "fa"}]}
            }
         }
      }
    }
 })
//...

I've made a fiddle with an example (there is used deprecated react-addons-update, but they have same behaviour).

NOTE: Your lagData is array. Shouldn't it be an object, since it is a state? In example above I've assumed that it should be and object, but if for some reasons you still have to deal with an array - here is the fiddle.

PS: Even more better, is to keep your state as an immutable object, for example with the help of this tool. I would suggest to loo towards it!