Learn React and Redux-Thunk By Building Netflix

I’m Hiep. I work as a full-time software engineer. Most of my open-source projects are focused on one thing – to help people learn ?.

Before moving on with this part, you should follow the first part and the second part in this series:

The first pa…

I’m Hiep. I work as a full-time software engineer. Most of my open-source projects are focused on one thing – to help people learn ?.

Before moving on with this part, you should follow the first part and the second part in this series:

The first part – Learn React By Building Netflix:

The second part – Learn Redux by Building Netflix:

The repository helps you learn Redux by buiding Netflix. It means that you are learning Redux by building a real-life project. I will explain concepts in detail. This post is the second part in my series and it is suitable for beginners.

Github link: https://github.com/hieptl/netflix-clone/tree/main/advanced/netflix-clone-with-redux-thunk

If you feel the repository is useful, please help me share the post and give me a ⭐. It will make me feel motivation to work even harder. I will try to make many open sources and share to the community.

I also created some series that help you improve your practical skills:

1. Master Design Patterns by Building Real Projects – Javascript.

Github: https://github.com/hieptl/master-javascript-design-patterns-by-building-real-projects

Blog: https://dev.to/hieptl/series/13039



Preface

This course will help you to learn Redux-Thunk by building Netflix. It means that you are learning by doing a real-life project.



Table of Contents



Table of Images.



0. How to Run the Project.

  • Step 1: Clone the project by using git clone or download the zip file.

  • Step 2: Open “terminal” / “cmd” / “gitbash” and change directory to “netflix-clone” and run “npm install” to install dependencies.

  • Step 3: Run “npm start” to run the fron-end project.



1. Live Demo.



2. Introduction about the Creator.



2.1. Greenwich University.

  • GPA 4.0 / 4.0.

  • Machine Learning paper – Recommendation System – IEEE/ICACT2020.

  • Co-Founder / Mentor IT club.



2.2. Hitachi Vantara Vietnam.

  • Employee of the year.

  • Second prize – innovation contest.

  • Techlead – HN branch.

  • One of CoE Leaders (Center of Excellence).



3. Prequisites.



3.1. Softwares.

  • Install NodeJS.

  • An IDE or a text editor (VSCode, Intellij, Webstorm, etc).



3.2. Technical Skills.

  • Basic programming skill.

  • Basic HTML, CSS, JS skills.



3.3. Materials.

  • Html, css, js (source code) was prepared because I want to focus on React and share knowledge about React. Building html and css from scratch would take a lot of time.

  • README.md (the md file will contain everything about the course).

  • Netflix data will be used to import to Firebase. In this course, we use Firebase as our back-end service.



4. Purposes of the Course.



4.1. Final Project.

  • The course would help you have understanding about React.

  • You could build the final project with end-to-end solution (front-end solution using React and back-end solution using Firebase).



4.2. Job.

  • After finishing the course, you could get a job with fresher / junior position.



5. Redux Middleware

  • It provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.



5.1. What is Thunk function.

  • A thunk is just a function which delays the evaluation of the value. It doesn’t take any arguments but gives the value whenever you invoke the thunk. i.e, It is used not to execute now but it will be sometime in the future. Let’s take a synchronous example,
const add = (x,y) => x + y;

const thunk = () => add(2,3);

thunk() // 5



5.2. What is Redux Thunk

  • “Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.” — Redux Thunk documentation



5.3. The Architecture of Redux Middlware


redux-middleware-architecture

Figure 1. Redux Middleware – Architecture.



5.4. Why

  • With a plain basic Redux store, you can only do simple synchronous updates by dispatching an action. Middleware extends the store’s abilities, and lets you write async logic that interacts with the store.

  • Thunks are the recommended middleware for basic Redux side effects logic, including complex synchronous logic that needs access to the store, and simple async logic like AJAX requests.



5.5. When

  • You can do synchronous updates by dispatching an action. In some cases, you need to perform asynchronous actions. It is time to use Redux Middleware.



5.6. How

Firstly, we need to understand the flow first.

  • The components will get state from the store. Whenever the state is changed, the components will be re-rendered.

  • The components will dispatch actions to tell the reducers update the state in the store.

  • In the case, we want to dispatch some asynchronous actions. The middleware will perform some side effects and get then pass the result to the reducers.

  • The reducers will take the responsibility to update the state. It will be used to return the latest state. In fact, we will not dispatch actions in the reducers. It is an anti-patten, we should avoid that.

In order to integrate Redux Thunk in our Netflix application, please follow the below steps:

  • Step 1: define the actions including the actions and the action’s types.

  • Step 2: define the reducers.

  • Step 3: define the store.

  • Step 4: Import redux-thunk and apply middleware to the store.

  • Step 5: Use the store in our application.

  • Step 6: Let our components get the state from the store.

  • Step 7: Let our components dispatch the actions to the store.



6. Build Login Feature by Using Redux and Redux Thunk – Netflix.


reduc-middleware-architecture

Figure 2. Login Page – Netflix.

In the first part of the series, we built the login feature by using pure React. In this part, we will refactor the code and re-build the login feature with supporting from Redux-Thunk.

  • Step 1: Install the Redux-Thunk by running npm install redux-thunk or yarn add redux-thunk

  • Step 2: Create services folder. The folder will be used to contain files which interact with the back-end.

  • Step 3: Create LoginService.js file in services folder. LoginService is used to perform auth feature.

// import firebase authentication.
import { firebaseAuth } from "../firebase/firebase";

export const login = (email, password) => {
  return firebaseAuth.signInWithEmailAndPassword(email, password);
};
  • Step 4: Create LoginAction.js in actions folder. The file will contain asynchronous actions such as login action, etc.
// import action types.
import * as loadingActionTypes from "./LoadingActionTypes";
// import login service.
import * as loginService from "../services/LoginService";

export const login = (email, password) => async (dispatch) => {
  try {
    dispatch({ type: loadingActionTypes.SHOW_LOADING });
    const userCredentials = await loginService.login(email, password);
    if (userCredentials) {
      console.log("Signed in user: ");
      console.log(userCredentials);
    }
    dispatch({ type: loadingActionTypes.HIDE_LOADING });
  } catch (error) {
    console.log(error);
  }
};

1st NOTE:

  • The login function is a thunk function. The dispatch parameter helps us dispatch other actions as needed.

  • In this case, we will the dispatch parameter to dispatch SHOW_LOADING ans HIDE_LOADING actions.

  • The login function accepts email and password as parameters.

  • We import all functions from LoginService.js as loginService and then call loginService.login to perform auth feature.

  • Step 5: In store.js, import thunk from ‘redux-thunk’ and then apply thunk to the store by using applyMiddleware.
// import create store and apply middleware.
import { createStore, applyMiddleware } from "redux";
// import root reducer.
import reducer from "./reducers";
// import thunk.
import thunk from "redux-thunk";

export default createStore(reducer, applyMiddleware(thunk));
  • Step 6: In LoginForm.js, we should perform auth feature by dispatching the login action.
// import react.
import { useState } from "react";
// import firebase authentication.
import { firebaseAuth } from "../../firebase/firebase";
// import use dispatch to dispatch action to the store.
import { useDispatch } from "react-redux";
// import actions.
import * as loginActions from "../../actions/LoginActions";

/**
 * create LoginForm component.
 */
function LoginForm() {
  // create email and password state to store user's credentials.
  const [email, setEmail] = useState();
  const [password, setPassword] = useState();

  // create dispatch instance to dispatch action to the store.
  const dispatch = useDispatch();
  /**
   * handle event when the user clicks on "Login" button.
   */
  const login = () => {
    dispatch(loginActions.login(email, password));
  };

  /**
   * update email state when the user inputs the email field.
   * @param {*} e - synthetic event to get the latest email's value.
   */
  const onEmailChanged = (e) => {
    // get email value.
    const updatedEmail = e.target.value;
    // update email state.
    setEmail(() => updatedEmail);
  };

  /**
   * update password state when the user input the password field.
   * @param {*} e - synthetic event to get the latest password's value.
   */
  const onPasswordChanged = (e) => {
    // get password value.
    const updatedPassword = e.target.value;
    // update password state.
    setPassword(() => updatedPassword);
  };

  return (
    <div className="login-body">
      <div className="login-body__form">
        <h1>Sign In</h1>
        <div className="login-body__input mb-16">
          <input
            type="text"
            placeholder="Email or phone number"
            onChange={onEmailChanged}
          />
        </div>
        <div className="login-body__input">
          <input
            type="password"
            placeholder="Password"
            onChange={onPasswordChanged}
          />
        </div>
        <button className="login-body__submit-btn" onClick={login}>
          Sign In
        </button>
        <div className="login-body__options">
          <span>Remember me</span>
          <span className="login-body__need-help">Need help?</span>
        </div>
        <div className="login-body__footer">
          <div className="login-body__fb">
            <img
              src="https://assets.nflxext.com/ffe/siteui/login/images/FB-f-Logo__blue_57.png"
              alt="fb"
            />
            <span>Login with Facebook</span>
          </div>
          <div className="login-body__new-to-nl">
            <span>New to Netflix ?</span>
            <span className="login-body__sign-up">Sign up now.</span>
          </div>
          <div className="login-body__google_captcha">
            This page is protected by Google reCAPTCHA to ensure you're not a
            bot.
            <span className="login-body__learn-more">Learn more.</span>
          </div>
        </div>
      </div>
    </div>
  );
}
// export LoginForm component.
export default LoginForm;

2nd NOTE:

  • We import useDispatch to dispatch action to the store.

  • We import loginAction, the loginAction.login action will be dispatched.

  • After running the code, you result should be like this.


reduc-middleware-architecture

Figure 3. The Final Result.



Summary

  • You can do synchronous updates by dispatching an action. In some cases, you need to perform asynchronous actions. It is time to use Redux Middleware.

  • Thunks are the recommended middleware for basic Redux side effects logic, including complex synchronous logic that needs access to the store, and simple async logic like AJAX requests.

  • applyMiddleware is used to apply middleware to the store.

  • In fact, we can apply multiple middlewares.

Thank you so much for taking the course. I hope that you could understand about Redux and you can build many real-life projects by using React (as front-end) and Firebase (as back-end) in order to solve many problems and make our life become better.



Useful Resources to Learn React.

[1]. https://reactjs.org/docs/getting-started.html.



References

[1]. https://reactjs.org/docs/getting-started.html. \
[2]. https://firebase.google.com/docs/database. \
[3]. https://firebase.google.com/docs/auth/web/password-auth. \
[4]. https://firebase.google.com/docs/hosting. \
[5]. https://redux.js.org/ \
[6]. https://github.com/reduxjs/redux-thunk


Print Share Comment Cite Upload Translate
APA
Hiep Le | Sciencx (2024-03-29T02:17:51+00:00) » Learn React and Redux-Thunk By Building Netflix. Retrieved from https://www.scien.cx/2021/06/10/learn-react-and-redux-thunk-by-building-netflix/.
MLA
" » Learn React and Redux-Thunk By Building Netflix." Hiep Le | Sciencx - Thursday June 10, 2021, https://www.scien.cx/2021/06/10/learn-react-and-redux-thunk-by-building-netflix/
HARVARD
Hiep Le | Sciencx Thursday June 10, 2021 » Learn React and Redux-Thunk By Building Netflix., viewed 2024-03-29T02:17:51+00:00,<https://www.scien.cx/2021/06/10/learn-react-and-redux-thunk-by-building-netflix/>
VANCOUVER
Hiep Le | Sciencx - » Learn React and Redux-Thunk By Building Netflix. [Internet]. [Accessed 2024-03-29T02:17:51+00:00]. Available from: https://www.scien.cx/2021/06/10/learn-react-and-redux-thunk-by-building-netflix/
CHICAGO
" » Learn React and Redux-Thunk By Building Netflix." Hiep Le | Sciencx - Accessed 2024-03-29T02:17:51+00:00. https://www.scien.cx/2021/06/10/learn-react-and-redux-thunk-by-building-netflix/
IEEE
" » Learn React and Redux-Thunk By Building Netflix." Hiep Le | Sciencx [Online]. Available: https://www.scien.cx/2021/06/10/learn-react-and-redux-thunk-by-building-netflix/. [Accessed: 2024-03-29T02:17:51+00:00]
rf:citation
» Learn React and Redux-Thunk By Building Netflix | Hiep Le | Sciencx | https://www.scien.cx/2021/06/10/learn-react-and-redux-thunk-by-building-netflix/ | 2024-03-29T02:17:51+00:00
https://github.com/addpipe/simple-recorderjs-demo