Simon Breton Simon Breton - 2 months ago 12
React JSX Question

How do I use d3.nest inside my react-reducer?

I've the following reducer :

const initialState = {data1:null, data2:null, isFetching: false,error:null};
export const gaData = (state = initialState, action)=>{
switch (action.type) {
case 'FETCH_DATA_SUCCESS':
return Object.assign(
{},state,
{data1: action.data1,
data2: action.data2.map( ([x, y, z]) => ({ x, y, z }) ),
isFetching: action.isFetching,
error: null });
default:return state;
}
};


How do I use
d3.nest
so I can nest
x
value and rollup
y
value for
data2
?

If I'm right I would to do something like this :

var newdata = d3.nest()
.key(function(d) { return d.x; })
.rollup(function(d) { return d3.sum(d, function(g) {return g.y;}); })
.entries(data2);


but I don't know do to include this in my reducer.

Answer

It sounds as though you just want to do something like this:

    case 'FETCH_DATA_SUCCESS':
        let data2 = action.data2.map(([x, y, z]) => ({ x, y, z }));
        data2 = d3.nest()
            .key(function (d) { return d.x; })
            .rollup(function (d) { return d3.sum(d, function (g) { return g.y; }); })
            .entries(data2);

Then you can just return data2 as part of the new state object.

As an aside, consider changing your variable name to something more meaningful than data2!

Comments