Using React
, Redux
, Redux-thunk
I want to have an initial state through a server request (API call) but I cannot seem to get this to work.
What I have got so far:
var Redux = require('redux');
var carReducer = require('./reducers/cars');
var thunk = require('redux-thunk').default;
var initialState = require('./reducers/initialState');
var rootReducer = Redux.combineReducers({
cars: carReducer
});
module.exports = Redux.applyMiddleware(thunk)(Redux.createStore)(rootReducer, initialState.loadInitial());
This is my initial store creation. My InitialState
looks like this:
var $ = require('jquery');
module.exports = {
loadInitial: loadInitial
};
function loadInitial() {
return {
cars: [
{}
]
}
}
When I try to turn this loadInitial
into a $.get('api/...')
, Redux tells me that I need an initial state in order for it to work.
In my reducer I have a load method:
function updateReducer(state, action) {
switch (action.type) {
case 'load':
return action.data;
case 'update':
return updateCars(action.data, state);
default:
return action.data || initialState.loadInitial().cars;
}
};
But again, if I use - as a default - an async call, it does not seem to work.
What I actually want is for my store to be initialized with whatever comes from the database. This is needed for my HandsonTable, since I pass the properties to the table and as I have it now, it will only render me one row because my initial state has only one object.
Weird part about this is that when I click on the table, it actually gets me all my rows because the data is loaded, but I'm guessing just too late.
Anyway, my question here is, how do I initialize my store through an api call to my backend?