0

as I understand, there is always a static initialState in reducer, now I want to async get the initial state from remote server, I know how to fetch them, and I could do this in componentWillMount in the related presentational component, but isn't it only use for presentation? where should I put below fetch code and get the initial state before it connect with store?

getInitailState = () => {
    return (
      fetch(apis.GETINITAILURL)
        .then((response)=>response.json())
        .then((responseJson) => {
            return responseJson;
        })
        .catch(e=>e)
    )
}

here is original full code for reducer:

import * as TYPES from '../actions/types.js';
import ApiUtils from '../utils/ApiUtils.js';

const initailTaskState = [{
    "taskid": 1,
    "priority": 3,
    "desc": "Bug fix",
    "timestamp": 5
}]

const tasks = (state = initailTaskState , action) => {
  switch(action.type){
    case TYPES.ADD_TASK:
        return [
            ...state,
            action.task
        ]
    case TYPES.DELETE_TASK:
        return state.filter( task => task.taskid !== action.taskid);

    default:
        return state

  }
}
export default tasks;
inoutwhy
  • 624
  • 1
  • 6
  • 12

1 Answers1

1

The fetch code should go inside an action creator. This action should be dispatched in componentWillMount. Do a fetch inside the action and dispatch another action which updates the store inside the success callback of fetch.

Also go through this thread. There is a good discussion on placing the API calls at correct places.

Swapnil
  • 2,573
  • 19
  • 30
  • Sorry I have never used thunk. But I found a great discussion on it over [here](http://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux). Even I am digesting it right now :p – Swapnil Jan 01 '17 at 08:48