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)
так же Вы должны указывать initialState, когда пишете редюсер:
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, если еще никаких диспатчев этого рюдесера не происходило.
}
Если Вам надо з сервера получить что-то, то подключаем thunkMiddleware и тогда делаем так:
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()