Created
December 29, 2015 17:06
-
-
Save flipjs/fbbf2ea7e50e1e47602b to your computer and use it in GitHub Desktop.
redux testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import ReactDOM from 'react-dom' | |
import {createStore, combineReducers, applyMiddleware} from 'redux' | |
// we need the thunk to delay the evaluation in async functions | |
import thunk from 'redux-thunk' | |
// Action Creators | |
// synchronous | |
const setName = name => ({ | |
type: 'SET_NAME', | |
name | |
}) | |
const addBook = book => ({ | |
type: 'ADD_BOOK', | |
book | |
}) | |
// async | |
const addBookAsync = book => { | |
return dispatch => { | |
setTimeout(() => { | |
dispatch(addBook(book)) | |
}, 1000) | |
} | |
} | |
const userReducer = (state = {}, action) => { | |
console.log('userReducer was called with state', state, 'and action', action) | |
switch (action.type) { | |
case 'SET_NAME': | |
return { | |
...state, | |
name: action.name | |
} | |
default: | |
return state | |
} | |
} | |
const booksReducer = (state = [], action) => { | |
console.log('booksReducer was called with state', state, 'and action', action) | |
switch (action.type) { | |
case 'ADD_BOOK': | |
return [ | |
...state, | |
action.book | |
] | |
default: | |
return state | |
} | |
} | |
const extraReducer = (state = [], action) => { | |
console.log('extraReducer was called with state', state, 'and action', action) | |
return state | |
} | |
const reducer = combineReducers({ | |
user: userReducer, | |
books: booksReducer, | |
extra: extraReducer | |
}) | |
// apply middleware | |
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore) | |
// create the store | |
const store = createStoreWithMiddleware(reducer) | |
// before dispatch | |
console.log('before ALL dispatch:', store.getState()) | |
// sync dispatch | |
console.log('setName will be dipatched...') | |
store.dispatch(setName('Flip JS')) | |
console.log('setName was just called and store has been changed to', store.getState()) | |
// async dispatch | |
console.log('addBook will be dipatched...') | |
store.dispatch(addBookAsync('The Art of War')) | |
console.log('addBook was just dispatched store has been changed to', store.getState()) | |
// after dispatch | |
console.log('after ALL dispatch:', store.getState()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment