Redux Example 2 Array CRUD
===========Step1========
Define Redux Slice: Create Slice (studentSlice.js)
-initState
-createSlice
-export action
-export default slice
import { createSlice } from '@reduxjs/toolkit';
//========== Initial State ==============
//==========1) State ============
const initialState = {
students: [
{ name: "Sabir", class: "BCA" },
{ name: "Ali", class: "MCA" }
],
stop: false,
index: 0
};
//========== Slice Definition ==========
const studentSlice = createSlice({
name: "StudentName",
initialState: initialState,
//==========2) Reducer
reducers: {
//============= Add Student =========
addStudent: (state, action) => {
state.students.push(action.payload); // Add new student to the array
},
//============= Update Student =========
updateStudent: (state, action) => {
const { index, updatedData } = action.payload;
if (state.students[index]) {
state.students[index] = updatedData; // Update student at specified index
}
},
//============= Delete Student =========
deleteStudent: (state, action) => {
const index = action.payload;
if (index >= 0 && index < state.students.length) {
state.students.splice(index, 1); // Remove student at specified index
}
}
}
});
//========= Export Actions and Reducer =========
export const { addStudent, updateStudent, deleteStudent } = studentSlice.actions;
export default studentSlice.reducer;
The provided code defines a slice in Redux Toolkit, which is a combination of the following:
- State: This is the
initialStatedefined in the slice. - Reducers: These are the functions like
addStudent,updateStudent, anddeleteStudentthat update the state. - Actions: These are automatically generated by Redux Toolkit for each reducer, such as
addStudent,updateStudent, anddeleteStudent.
===========Step2========
Configure Redux Slice: Create store (store.js)
-configure slice
import { configureStore } from '@reduxjs/toolkit';
import studentSlice from "./studentSlice";
const store = configureStore({
reducer: {
students: studentSlice
}
});
export default store;
===========Step3=========
Set Provider: Provider (index.js)
set code
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
Note : store={store} get from store config
import store from "./ReduxExample/Example1/features/store";
import {Provider} from "react-redux";
Store import created by you
and provider import from react-redux
Then set Structure in index.js look like this
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
============step4===========
This is final step where you
use redux (CRUD Operation AND UI)
Create TestRedux.js
import React, {useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {addStudent, deleteStudent, updateStudent} from "./features/studentSlice";
export default function () {
const students = useSelector((state) => state.students.students);
const dispatch = useDispatch();
const [name, setName] = useState('');
const [studentClass, setStudentClass] = useState('');
const [editIndex, setEditIndex] = useState(null);
//==========Add function===========
const handleAddStudent = () => {
if (name && studentClass) {
dispatch(addStudent({ name, class: studentClass })); // Create
setName('');
setStudentClass('');
}
};
//==========Update function===========
const handleUpdateStudent = () => {
if (editIndex !== null && name && studentClass) {
dispatch(updateStudent({
index: editIndex,
updatedData: { name, class: studentClass }
})); // Update
setName('');
setStudentClass('');
setEditIndex(null);
}
};
//==========Edit function===========
const handleEdit = (index) => {
setEditIndex(index);
setName(students[index].name);
setStudentClass(students[index].class);
};
//==========Delete function===========
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>
);
}
Comments
Post a Comment