Redux learning

Ivy Lyu
2 min readNov 10, 2019

I’m learning react-redux through building a shopping website, I wasn’t totally mastering it but I have to write something to clear my thoughts.

Config Redux

It takes time to config redux before implementing any functions related to this. The very first movement is to npm install react-redux redux and redux-logger. FYI, redux-logger is for debugging purposes.

After installation, I created a folder called redux, which stores all the redux stuff.

Reducer, action, and store

the store is a factory to store all the reducers; reducers kind of like react class that has the state and change the state according to actions. It gets the data from the app and does something with it, and it has the initial state and according to the action type, it can decide which value to return to the app; actions are functions that actually change the state.

It kind of fragmented to me, and sometimes I forget to add something and Idk where it is, so it can be annoying sometimes.

mapStateToProps() and mapDispatchToProps()

In short, mapStateToProps() is for subscribing to the state in the reducer file and mapDispatchToProps() is for selecting user triggers as actions passing to the store.

Redux scenario

  1. get current user

Get current user

I used firebase to do user authentication, which is easy to config. Before using redux, I get the current user from the DB and store them in the App.js state, but then I store them in the userReducer to get the user in every component.

In the App.js file, I write some methods to set the user info to the db, now I not only set the user to the db but also to the redux store by passing the setCurrentUser function as a prop and subscribe the state in the redux store, which is the user.currentUser, and then connect them together so when user state changes, the app UI will change.

componentDidMount() {const { setCurrentUser } = this.props;this.unsubscribFromAuth = auth.onAuthStateChanged(async userAuth => {if (userAuth) {const userRef = await createUserProfileDocument(userAuth);userRef.onSnapshot(snapShot => {  setCurrentUser({    id: snapShot.id,    ...snapShot.data()  });})}setCurrentUser(userAuth);})}......
<Route exact path='/signIn/' render={() => this.props.currentUser ? (<Redirect to='/' />) : (<SignInSignUpPage />)} />
.......const mapStateToProps = ({ user }) => ({currentUser: user.currentUser});const mapDispatchToProps = dispatch => ({setCurrentUser: user => dispatch(setCurrentUser(user))});export default connect(mapStateToProps, mapDispatchToProps)(App);

--

--