I
I
Igor Shumilovsky2015-12-09 16:58:51
JavaScript
Igor Shumilovsky, 2015-12-09 16:58:51

How to load data from JSON to initial store in redux?

I'm slowly getting to grips with Redux. I didn’t understand how this was done in the redux shopping cart example. There is data in json (for example, the same list of products). How to upload it to the store? Those. what is the route/pattern? Can you write examples of actions, reducers? Or explain to me how it works in the example above.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tassik, 2015-12-09
@JiSeven

import {createStore, combineReducers} from 'redux'
import {cardReducer, anotherReducer} from './reducers'

const reducer = combineReducers({
  cardReducers,
  anotherReducer
})

const initialState = { 
  // some data
  cardReducer: { 
    items: [{id: 1, name: 'book'}, {id: 2, name: 'some song'}]
    // etc
  },
  anotherReducer: { 
    //some another data
  }
}

const store = createStore(reducer, initialState)

you must also specify initialState when writing a reducer:
const initialState = {
  items: []
  // some another data
}
export function cardReducer(state = initialState, action) {
  switch(action.type) {
    case types.SOME_ACTION:
    // do some stuff
  default:
    return state // так же возвращается initialState, если еще никаких диспатчев этого рюдесера не происходило.
}

If you need to get something from the server, then connect thunkMiddleware and then do this:
const FETCH_ALL_ITEMS = 'FETCH_ALL_ITEMS'
const FETCH_ALL_ITEMS_SUCCESS = 'FETCH_ALL_ITEMS_SUCCESS'
const FETCH_ALL_ITEMS_ERROR = 'FETCH_ALL_ITEMS_ERROR'

export function fetchAllItemsFromServer() {
  return (dispatch, getState) => {
    dispatch({type: FETCH_ALL_ITEMS})
    fetch('http://example.com/account/card')
      .then(res => res.toJSON())
      .then(items => dispatch({type: FETCH_ALL_ITEMS_SUCCESS, payload: items}))
      .catch(errors => dispatch({type: FETCH_ALL_ITEMS_ERROR, errors: errors}))
  }
}

export function cardReducer(state = {
  items: [],
  isLoading: false,
  errors: {}
}, action) {
  switch (action.type) {
  case FETCH_ALL_ITEMS:
    return Object.assign({}, state, {
      isLoading: true
    })
  case FETCH_ALL_ITEMS_SUCCESS:
    return Object.assign({}, state, {
      isLoading: false,
      items: action.payload
    })
  case FETCH_ALL_ITEMS_ERROR:
    return Object.assign({}, state, {
      isLoading: false,
      errors: action.errors
    })
  default:
    return state
  }
}

// ну и теперь мы можем задиспатчить наш екшен
store.dispatch(fetchAllItemsFromServer())

// и потом изъять данные из стора
const state = store.getState()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question