React workshop

part 2 - redux

Mateusz Pokora Michał Gutowski Kamil Piotrowski

Binar::apps

Redux

Why do we need it?

Redux is a predictable state container for JavaScript apps.
 

  1. Unidirectional data flow (top -> down)
  2. state represented in single tree

Action

payloads of information that send data from your application to your store.

Action

  1. Add toeat (click button)
  2. Fetch collection from API (component mount / route enter)
  3.  
{
    type: 'ADD_TODO',
    todo: {...}
}

Action creators

Action creators are functions that create actions.

function addTodo(todo) {
    return {
        type: 'ADD_TODO',
        todo: todo
    }
}

Reducer

  1. Listen to actions
  2. Pure function
  3. No side effects
  4. input -> new state

 

Reducer

// reducer
const reducer = (state = defaultState, action ) => {
    switch(action.type) {
        case 'ADD_TODO':
            return [...state, action.todo];
        default: 
            return state;
    }
}

Containers

  1. connected to store
  2. listen to state changes
  3. access to store.dispatch()
  4. wrapped components
  5. hold any additional state and logic

Containers

import {connect} from 'react-redux';
import {toggle} from 'actions/toeats';
import ToeatList from 'components/toeat-list';

const mapStateToProps = (state) => {
  return {
    toeats: state.toeats
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onCheckItem: (name) => {
      dispatch(toggle(name));
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ToeatList);

Components

  1. Pure jsx components
  2. Render based on props only
  3. No side effects - same set of props renders exactly the same view

Coding time!

ToEat app on redux

 

  • Add toeat
  • Complete toeat
  • Remove toeat 
  • Fetch list

React - Redux

By vrael560

React - Redux

  • 373