Open In App

How to handle more action using redux ?

Improve
Improve
Like Article
Like
Save
Share
Report

In Redux, actions are the JavaScript object which has information. Having multiple actions will need multiple action creators. These actions should be unique in redux. Especially, the type of action must be defined properly to identify that.

We will take the example of to-do list actions. There are actions we will define and handle:

  • Add todo item
  • Delete todo item

Let’s create an application to demonstrate how to handle more action using redux.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app example

Step 2: After creating your project folder i.e. example, move to it using the following command:

cd example

Step 3: Module installation, now from the root directory of your project in the terminal, run the following command

npm install redux
npm install react-redux

Step 4: In src folder, make two new folder components and redux. In components add two jsx files named addTodo.jsx and listTodo.jsx. In redux folder, create a folder name actions and add index.js file to it. Then in redux folder create a folder name reducer and add two files named index.js and todoreducer.js. And then in redux folder add store.js file.

Project Structure: It will look like this.

Project Structure

Example: Let’s make a simple todo application with help of redux. Write down the following codes in respective files.

index.js




import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { Provider } from 'react-redux';
import App from './App';
import store from '../src/redux/store';
  
ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root'),
);


App.js




import AddTodo from './components/addTodo';
import ListTodo from './components/listTodo';
  
function App() {
  return (
    <div className="App">
     <h1>Todo List</h1>
     <AddTodo></AddTodo>
     <ListTodo></ListTodo>
    </div>
  );
}
  
export default App;


addTodo.jsx




import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addtodoitem } from '../redux/actions';
  
const AddTodo = () => {
  const [todo, setTodo] = useState('');
  const dispatch = useDispatch();
  return (
    <div>
      <h2>Enter the todo</h2>
      <label htmlFor="todoitem" />
      <input
        type="text"
        id="todoitem"
        value={todo}
        onChange={(e) => {
          setTodo(e.target.value);
        }}
      />
      <button
        onClick={() => {
          dispatch(
            addtodoitem({
              title: todo,
              done: false,
            }),
          );
          setTodo('');
        }}>
        Add todo
      </button>
    </div>
  );
};
  
export default AddTodo;


listTodo.jsx




import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { deltodoitem } from '../redux/actions';
  
const ListTodo = () => {
  const todos = useSelector((state) => state.todo);
  const dispatch = useDispatch();
  return (
    <div>
      {todos.map((todo, index) => (
        <div>
          <p style={{ display: 'inline', margin: '10px' }}>
            {todo.title}
          </p>
  
          <button
            onClick={() => {
              dispatch(deltodoitem(index));
            }}>
            Delete
          </button>
        </div>
      ))}
    </div>
  );
};
  
export default ListTodo;


redux/index.js




const addtodoitem = (item) => {
    return{
    type: "ADD_TODO",
    payload : item,
    };
};
  
const deltodoitem = (id) => {
    return{
    type: "DELETE_TODO",
    payload : id,
    };
};
  
export {addtodoitem,deltodoitem};


reducer/todoreducer.js




const todoreducer = (state = [], action) => {
  if (action.type === 'ADD_TODO') {
    return [...state, action.payload];
  }
  if (action.type === 'DELETE_TODO') {
    return state.filter((item, index) => index !== action.payload);
  }
  
  return state;
};
  
export default todoreducer;


reducer/index.js




import todoreducer from "./todoreducer";
import { combineReducers } from "redux";
  
const rootReducer = combineReducers({
    todo : todoreducer,
})
  
export default rootReducer;


redux/store.js




import rootReducer from "./reducer";
  
import { createStore } from "redux";
  
const store = createStore(rootReducer);
  
export default store;


We have defined the multiple actions of index.js file of the actions folder. They are using todoreducer file to perform the changes in the state of data of redux. This way we handle multiple actions in redux.

Step to run the application: Use the following command to run the application:

npm start

Output: Here, when we type in the input box and click on “Add todo” button ADD_TODO action is called and when we click on the “Delete” button DELETE_TODO is called. This way is able to handle two or more actions in redux.



Last Updated : 08 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads