React
Posted By Sebastian

Modern React From The Beginning EP12: Adding A Delete Action


Subscribe On YouTube

Episodes

In the last episode we’ve introduced the useReducer hook to manager out courses state in App component. So far, we’ve only implemented one action type in our reducer function: SET_COURSES. In this episode we’re going to enhance the reducer function by introducing another action typer for deleting a single course. Furthermore we’re implementing the necessary changes to add a Delete button and a corresponding click event handler function which is used to dispatch the new action type.

Adapting The Reducer Function

Let’s adapt the courseReducer function like you can see in the following code listing:

const coursesReducer = (state, action) => {
  switch(action.type) {
    case 'SET_COURSES':
      return action.payload;
    case 'REMOVE_COURSE':
      return state.filter(
        course => action.payload.id !== course.id
      );
    default: 
      throw new Error();
  }
};

Here we’ve added another case which is handling the action type REMOVE_COURSE. This action type is used to delete a single course item from the list of courses which is stored in the state. In order to remove the item we’re able to access the current state value via state, apply a filter by calling the filter method and then therewith removing the element from the array.

Implementing A Remove Course Handler

Now that we’ve enhanced the reducer function we need to add code which is needed to dispatch and invoke the REMOVE_COURSE action. We’ll do so by adding a button to each course item output and adding a click event handler function which is then invoking the corresponding remove action. The handleRemoveCourse function is implemented in App.js and looks like you can see in the following:

  const handleRemoveCourse = course => {
    dispatchCourses({
      type: 'REMOVE_COURSE',
      payload: course
    });
  }

Inside the event handler function we’re using the dispatchCourses function to dispatch the REMOVE_COURSE action. The current course item which should be deleted is assigned to the payload property of the object which is passed to dispatchCourses.

As we’ve implemented the handleRemoveCourse function within App.js, we also need to make it available inside of CoursesList component (because in CoursesList component we’re going to add the Delete button). This can be done by adding another component property:

<CoursesList courses={filteredCourses} handleRemoveCourse={handleRemoveCourse} />

Adding A Remove Button In CoursesList Component

Finally we’re ready to add the additional button to the JSX code of CoursesList component:

import React from 'react';

const CoursesList = ({courses, handleRemoveCourse}) => {
    return courses.map(course => {
      return (
        <div key={course.id}>
          <span>
            <a href={course.url}><h4>{course.title}</h4></a>
          </span>
          <span>by <strong>{course.author}</strong></span>
          <span>| Video Hours: {course.hours_video}</span>
          <span>| Number of Lectures: {course.number_of_lectures}</span>
          <span>| Rating: {course.rating}</span>
          <span>
            <button type="button" onClick={() => handleRemoveCourse(course)}>
              Remove
            </button>
          </span>
          <br/><br/>
        </div>
      );
    });
  }

  export default CoursesList;

The component is accepting the handleRemoveCourse prop and calling this event handler function inside the event handler for the click event of the button. The current course object is passed into that function call.

Advertisement: Top 3 React Online Courses

If you want to dive deeper and become a React pro also consider taking one of the following great online courses.

React – The Complete Guide (incl Hooks, React Router, Redux)*
Dive in and learn React.js from scratch! Learn Reactjs, Hooks, Redux, React Routing, Animations, Next.js and way more!

Go To Course*

Modern React with Redux*
Master React v16.6.3 and Redux with React Router, Webpack, and Create-React-App. Includes Hooks!

Go To Course*

The Complete React Developer Course (w/ Hooks and Redux)*
Learn how to build and launch React web applications using React, Redux, Webpack, React-Router, and more!

Go To Course*

* Affiliate Link / Advertisement: This blog post contains affiliate links, which means that if you click on one of the product links and buy a product, we’ll receive a small commission. There are no additional costs for you. This helps support the channel and allows us to continue to make videos like this. Thank you for the support!


Using and writing about best practices and latest technologies in web design & development is my passion.