Redux Example 1 Array CRUD

 

Example Application: Array CRUD Operations with Redux

Example Scenario: Managing an Array of Students

We’ll manage an array of student objects using Redux with CRUD operations.

Initial State:

const initialState = {
    students: [
        { name: "Sabir", class: "BCA" },
        { name: "Ali", class: "MCA" }
    ]
};

Slice (features/studentSlice.js):

import { createSlice } from '@reduxjs/toolkit';

const studentSlice = createSlice({
    name: 'students',
    initialState: {
        students: [
            { name: "Sabir", class: "BCA" },
            { name: "Ali", class: "MCA" }
        ]
    },
    reducers: {
        addStudent: (state, action) => {
            state.students.push(action.payload);
        },
        updateStudent: (state, action) => {
            const { index, updatedData } = action.payload;
            state.students[index] = updatedData;
        },
        deleteStudent: (state, action) => {
            state.students.splice(action.payload, 1);
        }
    }
});

export const { addStudent, updateStudent, deleteStudent } = studentSlice.actions;
export default studentSlice.reducer;

Store Configuration (store.js):

import { configureStore } from '@reduxjs/toolkit';
import studentReducer from './features/studentSlice';

const store = configureStore({
    reducer: {
        students: studentReducer
    }
});

export default store;

Step 3: Provide the Store to the React App

File: index.js


import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
    <Provider store={store}>
        <App />
    </Provider>
);

Step 4: Perform CRUD Operations in Components

File: App.js

Here, we’ll create a simple UI to add, update, and delete students.

import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addStudent, updateStudent, deleteStudent } from './studentsSlice';

const App = () => {
    const students = useSelector((state) => state.students); // Read students from Redux store
    const dispatch = useDispatch();

    const [name, setName] = useState('');
    const [studentClass, setStudentClass] = useState('');
    const [editIndex, setEditIndex] = useState(null);

    const handleAddStudent = () => {
        if (name && studentClass) {
            dispatch(addStudent({ name, class: studentClass })); // Create
            setName('');
            setStudentClass('');
        }
    };

    const handleUpdateStudent = () => {
        if (editIndex !== null && name && studentClass) {
            dispatch(updateStudent({
                index: editIndex,
                updatedData: { name, class: studentClass }
            })); // Update
            setName('');
            setStudentClass('');
            setEditIndex(null);
        }
    };

    const handleEdit = (index) => {
        setEditIndex(index);
        setName(students[index].name);
        setStudentClass(students[index].class);
    };

    const handleDelete = (index) => {
        dispatch(deleteStudent(index)); // Delete
    };

    return (
        <div>
            <h1>Student Management</h1>
            <div>
                <input
                    type="text"
                    placeholder="Name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                />
                <input
                    type="text"
                    placeholder="Class"
                    value={studentClass}
                    onChange={(e) => setStudentClass(e.target.value)}
                />
                {editIndex === null ? (
                    <button onClick={handleAddStudent}>Add Student</button>
                ) : (
                    <button onClick={handleUpdateStudent}>Update Student</button>
                )}
            </div>
            <ul>
                {students.map((student, index) => (
                    <li key={index}>
                        {student.name} - {student.class}
                        <button onClick={() => handleEdit(index)}>Edit</button>
                        <button onClick={() => handleDelete(index)}>Delete</button>
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default App;

Step 5: Explanation of CRUD Operations

  1. Create:

    • Add a new student by dispatching the addStudent action.
    • Example: dispatch(addStudent({ name: "John", class: "MCA" }));
  2. Read:

    • Display the list of students using useSelector to access the Redux state.
    • Example: const students = useSelector((state) => state.students);
  3. Update:

    • Edit a student by dispatching the updateStudent action with the index and new data.
    • Example: dispatch(updateStudent({ index: 0, updatedData: { name: "Sabir", class: "MCA" } }));
  4. Delete:

    • Remove a student by dispatching the deleteStudent action with the index.
    • Example: dispatch(deleteStudent(0));


Comments