My Todo

by Allie Yu

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/6.0.1/react-redux.min.js"></script>
<div id="root"></div>

Babel + JSX

/* 
Reducer : are functions that take “state” from Redux and “action” JSON object and returns a new “state” to be stored back in Redux.

1.Reducer functions are called by the “Container” containers when there is a user action. 

2.If the reducer changes the state, Redux passes the new state to each component and React re-renders each component
https://github.com/rajaraodv/redux/tree/master/examples
*/

const todo = (state, action) => {
  switch(action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      };
    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state;
      } //not same todo
      return Object.assign({}, state, {
        completed: !state.completed
      });
      //return { //same todo
      //	...state,
      //	completed: !state.completed
      //}; 
    default:
      return state;
  }
};

// todos reducer function
const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          completed: false
        }
      ];
    case 'TOGGLE_TODO':
      return state.map(todo =>
        (todo.id === action.id) 
          ? {...todo, completed: !todo.completed}
          : todo
      );
    default:
      return state;
  }
};

const visibilityFilter = (state = 'SHOW_ALL', action) => {
  switch(action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter;
    default:
      return state;
  }
};

const { combineReducers } = Redux;
const todoApp = combineReducers({
  // todos will be updated by the todos reducer function (and the same for the visiblity filter)
  todos, //same as --- todos: todos
  visibilityFilter
});

// action creator : tell you what kind of actions your components can do
// good replacement for inline dispatch calls (where you define an object as an argument to dispatch)

//Takes the text from 'AddTodo'...