Skip to content

State Management

Joshua C. Dargan edited this page Dec 7, 2021 · 3 revisions

Redux

Redux is a "predictable state container for JS [or TS] Apps". Redux is how we maange state within the application.

Redux Tutorial
https://redux.js.org/tutorials/essentials/part-2-app-structure

Redux Toolkit

Edugator was built using the create-react-app with the Redux Toolkit. See Redux Toolkit Getting Started and Redux Toolkit with TypeScript for more information.

Some react-toolkit tutorials that were good references:
https://redux.js.org/tutorials/essentials/part-2-app-structure#creating-the-redux-store
https://blog.logrocket.com/smarter-redux-with-redux-toolkit/
https://dev.to/nilanth/redux-toolkit-the-standard-way-to-write-redux-2g32

Redux Slices

Each page that needs some form of state across component uses Redux slices. Props are used if the child components is a direct child. To give state to grandchildren or greater, Redux Slices should be used. To create a slice, you should use the createSlice() function. You should create the reducer with all of the actions for that slice within the function object parameter and export all of the actions. Then you must add the slice's reducer to the rootReducer

This was an extremely helpful tutorial that helped me switch over to slices: https://www.youtube.com/watch?v=2hZhIoRuua4

rootReducer

The rootReducer combines all the reducers together using the combineReducers function.

Redux Sagas

Sagas are used as the middleware for the application and are crucial to creating state-sensitive API calls. Sagas are generator functions. You create a watcher saga which is later added to the root saga. The watcher saga will take every action of a specific type and pass the effect or action payload onto the appropriate saga function.

Watcher Saga

function* loginSaga() {
  yield takeEvery(requestLogin.type, handleRequestLogin);
}

Learn more here: https://redux-saga.js.org/docs/basics/DeclarativeEffects

Saga Middleware

rootSaga

A root Saga aggregates multiple Sagas to a single entry point for the sagaMiddleware to run.

The Store

The store is configured with the rootReducer and the saga middleware.

Axios

Axios is the promised based HTTP client used to create our API calls to the service side. We use the apiClient wrapper to perform our requests.

apiClient

The apiClient is a wrapper/interceptor on the request and response. The apiClient gives an authorization header to an API request if there is an authorization token stored in local storage. The apiClient checks if the response is an unauthorized error and if it is, removes the token and sets the error message. This can happen if the token is corrupted, expired, or otherwise invalid.

Axios Interceptors https://axios-http.com/docs/interceptors

Clone this wiki locally