inoutwhy
inoutwhy

Reputation: 624

react native get async initial state in reducer

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;

Upvotes: 0

Views: 1034

Answers (1)

Swapnil
Swapnil

Reputation: 2603

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.

Upvotes: 1

Related Questions