(ง •̀_•́)ง Ming and Her Code

References

All together practice

Redux Counter

const INCREMENT = "INCREMENT"; // define a constant for increment action types
const DECREMENT = "DECREMENT"; // define a constant for decrement action types

// define the counter reducer which will increment or decrement the state based on the action it receives
const counterReducer = (state = 0,action)=>{
    switch(action.type){
        case INCREMENT:
            return state+=1;
        case DECREMENT:
            return state-=1;
        default:
            return state;
    }
};

// define an action creator for incrementing
const incAction = ()=>{
    return {type:INCREMENT};
};

// define an action creator for decrementing
const decAction = ()=>{
return {type:DECREMENT};
};

// define the Redux store here, passing in your reducers
const store = Redux.createStore(
    counterReducer
);

console.log(store.getState());//0
store.dispatch(incAction());
console.log(store.getState());//1
store.dispatch(decAction());
console.log(store.getState());//0

ToDo list

const ADD_TO_DO = 'ADD_TO_DO';

// A list of strings representing tasks to do:
const todos = [
  'Go to the store',
  'Clean the house',
  'Cook dinner',
  'Learn to code',
];

const immutableReducer = (state = todos, action) => {
  switch(action.type) {
    case ADD_TO_DO:
      // don't mutate state here or the tests will fail
      return [...state, action.todo]
    default:
      return state;
  }
};

// an example todo argument would be 'Learn React',
const addToDo = (todo) => {
  return {
    type: ADD_TO_DO,
    todo
  }
}

const store = Redux.createStore(immutableReducer);

Redux

Redux is a state management framework/predictable state container for JavaScript apps, that can be used with a number of different web technologies including React. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.

//redux store: the Redux store is the single source of truth when it comes to application state.
const reducer = (state = 5) => {
  return state;
}
//create a store
let store = Redux.createStore(reducer);

//get state from the store
const store = Redux.createStore(
  (state = 5) => state
);
let currentState = store.getState();

//define a Redux Action
let action={
    type:"LOGIN"
};

//define an action creator
const action = {
  type: 'LOGIN'
}

function actionCreator(){
  return action;
}

//dispatch an action event
store.dispatch(actionCreator());
store.dispatch({ type: 'LOGIN' });

//reducer function: respond to the action after it's been created and dispatched
const reducer = (state = defaultState, action) => {//take state and action as arguments
  return action.type==="LOGIN"?{login:true}:state;//always return a new copy of the state(state is read-only)
};


//use const for action type
const LOGIN = "LOGIN";
const LOGOUT = "LOGOUT";

//use a switch statement to handle multiple actions
const authReducer = (state = defaultState, action) => {
  switch (action.type) {
    case LOGIN:
      return {
        authenticated: true
      }

    case LOGOUT:
      return {
        authenticated: false
      }

    default:
      return state;

  }
};

const loginUser = () => {
  return {
    type: LOGIN
  }
};

const logoutUser = () => {
  return {
    type: LOGOUT
  }
};

//register a store listener(store.subscribe()): another method that access Redux store
const ADD = 'ADD';
const reducer = (state = 0, action) => {
  switch(action.type) {
    case ADD:
      return state + 1;
    default:
      return state;
  }
};
const store = Redux.createStore(reducer);
// global count variable:
let count = 0;
store.subscribe(()=>{
  count++;
})
store.dispatch({type: ADD});
console.log(count);//1
store.dispatch({type: ADD});
console.log(count);//2
store.dispatch({type: ADD});
console.log(count);//3

//combine multiple reducer: Redux.combineReducers()
const rootReducer = Redux.combineReducers({//example of a note-taking app with authentication
  auth: authenticationReducer,
  notes: notesReducer
});

//send action data to the store
const ADD_NOTE = 'ADD_NOTE';

const notesReducer = (state = 'Initial State', action) => {
  switch(action.type) {
    case ADD_NOTE:
      return action.text
    default:
      return state;
  }
};

const addNoteText = (note) => {
  return {
    type:ADD_NOTE,
    text:note
  }
};

const store = Redux.createStore(notesReducer);

console.log(store.getState());//initial state
store.dispatch(addNoteText('Hello!'));
console.log(store.getState());//hello

//Redux Thunk middleware: handle asynchronous actions
const REQUESTING_DATA = 'REQUESTING_DATA'
const RECEIVED_DATA = 'RECEIVED_DATA'

const requestingData = () => { return {type: REQUESTING_DATA} }
const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} }

const handleAsync = () => {
  return function(dispatch) {
    store.dispatch(requestingData());
    setTimeout(function() {
      let data = {
        users: ['Jeff', 'William', 'Alice']
      }
    store.dispatch(receivedData(data));
    }, 2500);
  }
};

const defaultState = {
  fetching: false,
  users: []
};

const asyncDataReducer = (state = defaultState, action) => {
  switch(action.type) {
    case REQUESTING_DATA:
      return {
        fetching: true,
        users: []
      }
    case RECEIVED_DATA:
      return {
        fetching: false,
        users: action.users
      }
    default:
      return state;
  }
};

const store = Redux.createStore(
  asyncDataReducer,
  Redux.applyMiddleware(ReduxThunk.default)
);

//copy object
const defaultState = {
  user: 'CamperBot',
  status: 'offline',
  friends: '732,982',
  community: 'freeCodeCamp'
};

const immutableReducer = (state = defaultState, action) => {
  switch(action.type) {
    case 'ONLINE':
      // don't mutate state here or the tests will fail
      return Object.assign({},state,{status:"online"})
    default:
      return state;
  }
};

const wakeUp = () => {
  return {
    type: 'ONLINE'
  }
};

const store = Redux.createStore(immutableReducer);