# Redux

## Definition

* Redux is a library for managing and updating application state library which is one-way data flow

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-MZEDqD0EY51qOJ9qy3K%2F-MZEENUvqgc9qWn71Kjj%2Fimage.png?alt=media\&token=c2f9cc43-7296-4263-9751-54e2b9076e7e)

* Redux only have one store which can be an object and be used globally
* Components will subscribe to the store and the store will notify to its component when changes
* Reducer is used to take the input and update the store
* When component want to make change to the store, it needs to dispatch the action which is described the the changes, and reducer take the action as a input and change the store&#x20;

## Reducer

1. Contain different business logics and return different states based on the actions.
2. Should be a pure function (not contain other data sources, such as api)

* Example:

```javascript
import { combineReducers } from "redux";
interface product {
  name: string;
  price: number;
  qty: number;
  type: number;
}

interface receipt {
  subtotal: number;
  total: number;
  tax: number;
}

const defaultReceipt: receipt = {
  subtotal: 0,
  total: 0,
  tax: 0,
};

interface action {
  type: string;
  content: receipt;
}

const receipt = (state = defaultReceipt, actions: action) => {
  switch (actions.type) {
    case "SET_RECEIPT": {
      return actions.content;
    }
    default:
      return state;
  }
};

const productList = (state = [], actions: action) => {
  switch (actions.type) {
    case "SET_LIST": {
      return actions.content;
    }
    default:
      return state;
  }
};

const ReceiptApp = combineReducers({
  receipt,
  productList,
});

export default ReceiptApp;
```

## Store

1. The whole global state of your app is stored in an object tree inside a single store.&#x20;
2. Dispatch method is to send the action to reducer to change the state tree

* Example:

```javascript
import { Provider } from "react-redux";
import ReceiptApp from "./reducers";
import { createStore } from "redux";

let store: any = createStore(ReceiptApp, {});

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);
```

* Example (dispatch):

```javascript
import { useDispatch } from "react-redux";
import { setReceipt, setProductList } from "../actions";

const Inputform: React.FC<{
  createReceipt: (input: receipt) => void;
  createProductList: (input: product[]) => void;
}> = ({ createReceipt, createProductList }) => {
  const dispatch = useDispatch();
  const createReceipt = (input: receipt) => {
      dispatch(setReceipt(input));
  }
  const createProductList = (input: product[]) => {
      dispatch(setProductList(input));
  }
  ...
}

export default Inputform;
```

* Example (get the state):

```javascript
import { useSelector } from "react-redux";

const Receipt: React.FC<{
}> = () => {
  const receiptData:receipt = useSelector((state) => state.receipt);
  const productListData:product[] = useSelector((state) => state.productList);
  ...
}

export default Receipt;
```

## Action

1. Type is to describe the name of event happened
2. Content/Payload is to describe the change after event&#x20;
3. After dispatching the action, it will pass the argument to the reducer to perform business logic and changed the state tree

* Example:

```javascript
export const setReceipt = (input: receipt) => {
  //console.log(input);
  return {
    type: "SET_RECEIPT",
    content: input,
  };
};

export const setProductList = (input: product[]) => {
  //console.log(input);
  return {
    type: "SET_LIST",
    content: input,
  };
};
```

## Redux Saga

#### Why Saga?

If we involve the the business logic related to async function (such api call), we need saga to implement it instead of doing it in the reducer, since reducer should be a pure function, also the promise function will be returned instead of the resolve value if the reducer becomes a async function

#### Flow

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MFW3x2aqEO8GF2kr3VU%2F-MNNXiFa_wWP-fxebDab%2F-MNNZ_rpViH6MPZ4SXKu%2F%E8%9E%A2%E5%B9%95%E6%88%AA%E5%9C%96%202020-11-30%20%E4%B8%8B%E5%8D%885.52.32.png?alt=media\&token=cde97a97-6e25-46d7-9e27-92946acd4a4d)

#### Pre-Condition

```bash
npm install redux-saga
```

#### Link With reducer

* We create rootSaga , apply the saga middleware with reducer to the store and run the rootSaga

```javascript
// index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import Count from "./redux/reducer";
import { applyMiddleware, createStore } from "redux";
import createSagaMiddleware from "redux-saga";
import rootSaga from "./saga";

const sagaMiddleWare = createSagaMiddleware();
const store = createStore(Count, applyMiddleware(sagaMiddleWare));
sagaMiddleWare.run(rootSaga);
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);
```

#### RootSaga

* Divided into 2 parts - worker and watcher
* Worker: Containing logic to implementing the async function ( use call method) and trigger the existing action ( use put method)
* Watcher: Monitoring the specific action, if the type of specific action is called, the function of the worker will be triggered, monitoring function mainly contain 2 types : takeLatest and takeEvery. takeLatest: If the previous worker still not finished, the new worker will start and the previous one will be cancelled. takeEvery: even the previous worker is not finished, the new worker can be triggered, and the previous worker is still running at the same time

```javascript
import {
  delay,
  put,
  takeEvery,
  all,
  takeLatest,
  call,
} from "redux-saga/effects";
import {
  addCount,
  minCount,
  addAsync,
  getApiData,
  getApiDataAsync,
} from "../redux/action";
import { callAPI } from "../api";

// Saga Worker
function* addAsyncSaga() {
  yield delay(1000);
  yield put(addCount());
}

function* getApiDataSaga() {
  const data = yield call(callAPI, "https://sampleapis.com/futurama/api/info");
  yield put(getApiData(data));
}

// Saga Watcher
export default function* rootSaga() {
  yield all([
    takeLatest(addAsync().type, addAsyncSaga),
    takeLatest(getApiDataAsync().type, getApiDataSaga),
  ]);
}
```

## Redux Toolkit

#### Why need redux toolkit

* The action is structured, contains payload and type,
* createSlice automatically generates a slice reducer with corresponding action creators and action types. so longer need to map the reducer and action by type
* As the state is immutable, if you need to change the value, you must need to return new object and do the logic on it

```javascript
function plainJsReducer(state, action) {
  // Add 3 points to Ravenclaw,
  // when the name is stored in a variable
  const key = "ravenclaw";
  return {
    ...state, // copy state
    houses: {
      ...state.houses, // copy houses
      [key]: {  // update one specific house (using Computed Property syntax)
        ...state.houses[key],  // copy that specific house's properties
        points: state.houses[key].points + 3   // update its `points` property
      }
    }
  }
}
```

* By using redux-toolkit, since its reducer function already include immer, so you can change the value with user-friendly syntax without mutating the state

```javascript
function immerifiedReducer(state, action) {
  const key = "ravenclaw";

  // produce takes the existing state, and a function
  // It'll call the function with a "draft" version of the state
  return produce(state, draft => {
    // Modify the draft however you want
    draft.houses[key].points += 3;

    // The modified draft will be
    // returned automatically.
    // No need to return anything.
  });
}
```

#### Implementation

* Main (Group the slices together)

```javascript
import { combineReducers } from "@reduxjs/toolkit";
import roomReducer from "./slice/roomSlice";
import userReducer from "./slice/userSlice";

const rootReducer = combineReducers({
  roomInfo: roomReducer,
  userInfo: userReducer,
});

export type RootState = ReturnType<typeof rootReducer>;
export default rootReducer;
```

* Slice (Define reducer and action and their relationship)

```javascript
import { createSlice, PayloadAction } from "@reduxjs/toolkit";

type roomState = {
  name: string;
};

const roomInfoSlice = createSlice({
  name: "roomInfo",
  initialState: { name: "New Room" },
  reducers: {
    setCurrentRoomName(room, action: PayloadAction<string>) {
      //console.log(action, room);
      const { payload } = action;
      room.name = payload;
      //return room;
    },
  },
});

export const { setCurrentRoomName } = roomInfoSlice.actions;

export default roomInfoSlice.reducer;
```

* Store

```typescript
import React from "react";
import ReactDOM from "react-dom";
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Dashboard from "./pages/dashboard";
import Index from "./pages";
import { Provider } from "react-redux";
import rootReducer from "./reducer";
import { configureStore } from "@reduxjs/toolkit";

const store = configureStore({ reducer: rootReducer });

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <div>
        <Switch>
          <Route path="/dashboard" component={Dashboard} />
          <Route path="/" component={Index} />
        </Switch>
      </div>
    </Router>
  </Provider>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
```

* Dispatch

```typescript
import React from "react";
import { useDispatch } from "react-redux";
import { setCurrentRoomName } from "../../reducer/slice/roomSlice";
const ChatRoomCard: React.FC<{
  name: string;
  switchToRoom: () => void;
}> = ({ name = "", switchToRoom }) => {

  const dispatch = useDispatch();
  
  const enterRoom = () => {
    dispatch(setCurrentRoomName(name));
    switchToRoom();
  };

  return (
    ...
  )
};

export default ChatRoomCard;

```

* State

```typescript
import React from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../reducer";
const Header: React.FC<{
  switchToMenu: () => void;
}> = ({ switchToMenu }) => {
  const { name } = useSelector((state: RootState) => state.roomInfo);
  return (
     ...
  );
};

export default Header;
```

##
