Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

How should you React to Redux

3,497 views

Published on

As presented at DevDuck #3 - JavaScript meetup for developers (www.devduck.pl)
___

All you need to know about using React with Redux

-----
Looking for a company to build you an electron desktop app? www.brainhub.eu

Published in: Software
  • Login to see the comments

How should you React to Redux

  1. 1. How should you React to Redux
  2. 2. What's redux?
  3. 3. Redux State container Implements Flux
  4. 4. Unidirectional
  5. 5. Actions actions don't do anything only contain information have no idea how to update a store
  6. 6. Actions function addTodo(task) { return { type: 'ADD_TODO', payload: task, }; }
  7. 7. Actions - test describe('TodoAction creator', () => { it('should create ADD_TODO action', () => { const expectedAction = { type: 'ADD_TODO', payload: 'test', }; expect(todoAction('test')).to.be.deep.equal(expectedAction); }); });
  8. 8. Dispatcher can register stores (listeners) sends actions to all stores (listeners) have no idea how to update a store
  9. 9. Store listens for actions creates new state from old state and action knows how to update a store
  10. 10. Store - reducer function todoReducer(state = initialState, action) { switch (action.type) { case 'ADD_TODO': return { ...state, list: [ ...state.list, action.payload, ], }; default: return state; } }
  11. 11. Reducer - test describe('todoReducer', () => { it('should return initial state', () => { expect(todoReducer(undefined, {})).to.be.deep.equal(initialState); }); it('should add element to list', () => { const name = 'testName'; const action = { type: 'ADD_TODO', payload: name, }; const expectedState = { list: [ name, ], }; expect(todoReducer(initialState, action)).to.be.deep.equal(expectedState); }); });
  12. 12. View represents current state can should listen for store updates have no idea how to update a store
  13. 13. class TodoList extends Component { static propTypes = { list: PropTypes.array, }; render() { const { list } = this.props; return (<div> <ul> {list.map(element => <li key={key}>{element}</li>)} </ul> </div> ); } } export default connect( state => ({ list: state.todo.list, }) )(TodoList);
  14. 14. How to update the state? view can send action to dispatcher have no idea how to update a store does not have to know what happens next only what it wants to achieve
  15. 15. class TodoList extends Component { static propTypes = { list: PropTypes.array, addItem: PropTypes.func, }; render() { const { list } = this.props; return (<div> <button onClick={() => this.props.addItem('New item')}/> <ul> {list.map(element => <li key="{key}">{element}</li>)} </ul> </div> ); } } export default connect( state => ({ list: state.todo.list, }), { addItem, } )(TodoList);
  16. 16. Let's code!
  17. 17. Thank you!

×