Simon Breton Simon Breton - 3 months ago 16
React JSX Question

How do I deal with d3.json to get my InitialState in React/redux

Using React/Redux, I'm trying to get external data into my initial state with express. I'm used to work with D3 so I wanted to use d3.json with my reducer like this :

var url = 'http://localhost:3000/authors';

function cool() {
d3.json(url, function(data) {
dataset = data;
});
}

const authorData = (state = dataset, action) => {
switch (action.type) {
case 'DATA_CHART_ALL':
return action.data
case 'DATA_CHART_FILTER':
return action.data
default:
return state;
}
};

export default authorData;


Since D3.json is a callback function, my reducer is returned undefined. How do I deal with this ? Can I use something else than d3.json ?

Answer

You need a function that will act as a dispatcher in redux:

// redux action using a dispatcher (think middleware)
export function cool(url) {
    return function(dispatch) {
        return d3.json(url, response => {
            dispatch(setData(response))
        }
    }
}

// redux action
export function setData(data) {
 return {
        type: 'DATA_CHART_ALL',
        data
    }
}

const authorDataReducer = (state = {}, action) => {
    switch (action.type) {
      case 'DATA_CHART_ALL':
        return action.data
      case 'DATA_CHART_FILTER':
        return action.data
      default:
        return state;
    }
};

export authorDataReducer;

to use it:

call this at the beginning of your application:

store.dispatch(cool("MY_URL"));

Note that i'm not checking for error handling in the request

Comments