Wednesday, November 20, 2024
Google search engine
HomeLanguagesHow are actions defined in Redux ?

How are actions defined in Redux ?

Redux is the state management library for JavaScript apps. It is used to manage the data globally in the app. In redux, there are basically three parts:

  1. Actions 
  2. Reducer
  3. Store

Actions: Actions are the JavaScript object which have information. Actions provide information for the store. Actions have a type field that identifies what kind of action to perform and all other fields contain information or data. 

There is one more term which is used to create the action called Action creator, there are simple function which create fun and return the action object.

Syntax:

function fun_name(parameters) {
  return { // action object
    type: 'TYPE_NAME', 
    task: task
  }
}

Let’s create an application to demonstrate how actions are defined:

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

Now from the root directory of your project terminal, run the following command

npm install redux
npm install react-redux

Example: Let’s make a simple todo application with help of redux.

In src folder, make two new folder components and redux.

In components add two jsx files

  • addTodo.jsx
  • listTodo.jsx

In redux folder

  • Create a folder named actions and add a file index.js inside actions folder.
  • Create a folder named reducer and add two files index.js and todoreducer.js inside it.
  • Create js file store.js

Project Structure will look like this:

Project Structure

Let’s make the files of the app as follows:

Filename: index.js inside src

Javascript




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


Filename: App.js inside src

Javascript




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;


In components folder these files as follows

Filename: addTodo.jsx

Javascript




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"></label>
      <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;


Filename: listTodo.jsx

Javascript




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;


In redux folder these files as follows

Filename: index.js of actions folder

Here two actions are defined with help of the action creator.

Javascript




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


Filename : todoreducer.js of reducer folder

Javascript




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


Filename: index.js of reducer folder

Javascript




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


Filename: store.js inside redux folder

Javascript




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


After setting up all the files,

from the terminal run the following command to start the app to run

npm start

Output: 

Output

This way we added two actions in the above example which add and delete the items from the list.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments