Settings page in SUSI.AI earlier implemented using Flux needed to be migrated to Redux, Redux integration eases handling of global state management. With Redux being integrated with Settings, the code could be split into smaller manageable components. Earlier implementation involved passing data to other Settings Tab and using Settings component as a state source. This resulted in Settings component getting more lines of code(~1300 LOC). After using Redux, only ~280 LOC is present in settings component file, and separate files for each settings tab view.
Once user login, the App component fetches User Settings in ComponentDidMount.
The action getUserSettings fetch users settings from apis.getUserSettings and populates the store settings using SETTINGS_GET_USER_SETTINGS reducer function.
The store consists of all the settings required for persisting data.
SETTINGS_GET_USER_SETTINGS sets the settings store from API payload. The customThemeValue is an object, which is populated once the settings are fetched and the string is split into array.
The payload contains the updated state, the reducer returns a new state with payload appended.
The setUserSettings action updates the settings store, once the user presses the Save Button in the Settings Tab.
Redux integration in the component
Redux is used in ChatAppTab as: The local state of ChatAppTab is initialized with redux store state. Using mapStateToProps we can access enterAsSend object from the redux store.
The connect function connects the React component with Redux store and injects props and actions into our component using HOC pattern. It injects data from the store and functions for dispatching actions to store.
Injecting props in local components:
Once a user makes a change in the tab and saves it, we need to dispatch an action to modify our prop enterAsSend inside the redux store.
handleSubmit is invoked when user presses the Save Button, action.setUserSettings is dispatched once API returns accepted: true response.
To conclude, the removal of flux and integration of redux gave the advantage of making the code more modular and separate the logic into smaller files. In the future, more settings can be easily added using the same data flow pattern.
- Migrating to Redux from flux: https://redux.js.org/recipes/migrating-to-redux
- Why use Redux- https://blog.logrocket.com/why-use-redux-reasons-with-clear-examples-d21bffd5835/
- Documentation of Redux – https://redux.js.org/
- React Anti-Pattern: Prop-Drilling – https://codeburst.io/react-anti-pattern-prop-drilling-54474d5236bd
- Redux connect – https://react-redux.js.org/api/connect
- Link to the PR: https://github.com/fossasia/susi.ai/pull/2129
SUSI.AI, FOSSASIA, GSoC19, Redux, SUSI Chat, Settings