Get and Delete API's implemented using redux
This commit is contained in:
parent
575e122b02
commit
9220143bbb
|
@ -45,7 +45,7 @@ const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({ open, handl
|
|||
onSubmit: handleSubmit(onSubmit),
|
||||
}}
|
||||
>
|
||||
<DialogTitle>{editRow ? "Editwefwefwe" : 'Add'} Category</DialogTitle>
|
||||
<DialogTitle>{editRow ? "Edit" : 'Add'} Category</DialogTitle>
|
||||
<DialogContent>
|
||||
<Controller
|
||||
name="category"
|
||||
|
|
|
@ -45,7 +45,7 @@ const AddEditTagsModal: React.FC<AddEditTagsModalProps> = ({ open, handleClose,e
|
|||
onSubmit: handleSubmit(onSubmit),
|
||||
}}
|
||||
>
|
||||
<DialogTitle>{editRow ? "Editsefwefwe" : 'Add'} Tag</DialogTitle>
|
||||
<DialogTitle>{editRow ? "Edit" : 'Add'} Tag</DialogTitle>
|
||||
<DialogContent>
|
||||
<Controller
|
||||
name="tag"
|
||||
|
|
|
@ -1,187 +1,225 @@
|
|||
import * as React from 'react';
|
||||
import { styled } from '@mui/material/styles';
|
||||
import Table from '@mui/material/Table';
|
||||
import TableBody from '@mui/material/TableBody';
|
||||
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
|
||||
import TableContainer from '@mui/material/TableContainer';
|
||||
import TableHead from '@mui/material/TableHead';
|
||||
import TableRow from '@mui/material/TableRow';
|
||||
import Paper, { paperClasses } from '@mui/material/Paper';
|
||||
import * as React from "react"
|
||||
import { styled } from "@mui/material/styles"
|
||||
import Table from "@mui/material/Table"
|
||||
import TableBody from "@mui/material/TableBody"
|
||||
import TableCell, { tableCellClasses } from "@mui/material/TableCell"
|
||||
import TableContainer from "@mui/material/TableContainer"
|
||||
import TableHead from "@mui/material/TableHead"
|
||||
import TableRow from "@mui/material/TableRow"
|
||||
import Paper, { paperClasses } from "@mui/material/Paper"
|
||||
import { deleteAdmin } from "../../redux/slices/authSlice"
|
||||
import { useDispatch } from "react-redux"
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
dividerClasses,
|
||||
IconButton,
|
||||
listClasses,
|
||||
Menu,
|
||||
} from '@mui/material';
|
||||
import MoreVertRoundedIcon from '@mui/icons-material/MoreVertRounded';
|
||||
Box,
|
||||
Button,
|
||||
dividerClasses,
|
||||
IconButton,
|
||||
listClasses,
|
||||
Menu,
|
||||
} from "@mui/material"
|
||||
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded"
|
||||
import DeleteModal from "../Modals/DeleteModal/DeleteModal"
|
||||
import { AppDispatch } from "../../redux/store/store"
|
||||
|
||||
// Styled components for customization
|
||||
const StyledTableCell = styled(TableCell)(({ theme }) => ({
|
||||
[`&.${tableCellClasses.head}`]: {
|
||||
backgroundColor: ' #1565c0',
|
||||
color: theme.palette.common.white,
|
||||
},
|
||||
[`&.${tableCellClasses.body}`]: {
|
||||
fontSize: 14,
|
||||
},
|
||||
}));
|
||||
[`&.${tableCellClasses.head}`]: {
|
||||
backgroundColor: " #1565c0",
|
||||
color: theme.palette.common.white,
|
||||
},
|
||||
[`&.${tableCellClasses.body}`]: {
|
||||
fontSize: 14,
|
||||
},
|
||||
}))
|
||||
|
||||
const StyledTableRow = styled(TableRow)(({ theme }) => ({
|
||||
'&:nth-of-type(odd)': {
|
||||
backgroundColor: theme.palette.action.hover,
|
||||
},
|
||||
'&:last-child td, &:last-child th': {
|
||||
border: 0,
|
||||
},
|
||||
}));
|
||||
"&:nth-of-type(odd)": {
|
||||
backgroundColor: theme.palette.action.hover,
|
||||
},
|
||||
"&:last-child td, &:last-child th": {
|
||||
border: 0,
|
||||
},
|
||||
}))
|
||||
|
||||
interface Column {
|
||||
id: string;
|
||||
label: string;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
id: string
|
||||
label: string
|
||||
align?: "left" | "center" | "right"
|
||||
}
|
||||
|
||||
interface Row {
|
||||
[key: string]: any;
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
interface CustomTableProps {
|
||||
columns: Column[];
|
||||
rows: Row[];
|
||||
setDeleteModal: Function;
|
||||
setRowData: Function;
|
||||
setModalOpen: Function;
|
||||
columns: Column[]
|
||||
rows: Row[]
|
||||
setDeleteModal: Function
|
||||
setRowData: Function
|
||||
setModalOpen: Function
|
||||
deleteModal: boolean
|
||||
}
|
||||
|
||||
const CustomTable: React.FC<CustomTableProps> = ({
|
||||
columns,
|
||||
rows,
|
||||
setDeleteModal,
|
||||
setRowData,
|
||||
setModalOpen,
|
||||
columns,
|
||||
rows,
|
||||
setDeleteModal,
|
||||
deleteModal,
|
||||
setRowData,
|
||||
setModalOpen,
|
||||
}) => {
|
||||
console.log('columnsss', columns, rows);
|
||||
// console.log("columnsss", columns, rows)
|
||||
const dispatch = useDispatch<AppDispatch>()
|
||||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
|
||||
const [selectedRow, setSelectedRow] = React.useState<Row | null>(null)
|
||||
const open = Boolean(anchorEl)
|
||||
|
||||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||
const open = Boolean(anchorEl);
|
||||
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
};
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null);
|
||||
};
|
||||
|
||||
const isImage = (value: any) => {
|
||||
if (typeof value === 'string') {
|
||||
return value.startsWith('http') || value.startsWith('data:image'); // Check for URL or base64 image
|
||||
const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
|
||||
setAnchorEl(event.currentTarget)
|
||||
setSelectedRow(row) // Ensure the row data is set
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
return (
|
||||
<TableContainer component={Paper}>
|
||||
<Table sx={{ minWidth: 700 }} aria-label="customized table">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{columns.map((column) => (
|
||||
<StyledTableCell key={column.id} align={column.align || 'left'}>
|
||||
{column.label}
|
||||
</StyledTableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rows.map((row, rowIndex) => (
|
||||
<StyledTableRow key={rowIndex}>
|
||||
{columns.map((column) => (
|
||||
<StyledTableCell key={column.id} align={column.align || 'left'}>
|
||||
{isImage(row[column.id]) ? (
|
||||
<img
|
||||
src={row[column.id]}
|
||||
alt="Row "
|
||||
style={{
|
||||
width: '50px',
|
||||
height: '50px',
|
||||
objectFit: 'cover',
|
||||
}}
|
||||
/>
|
||||
) : column.id !== 'action' ? (
|
||||
row[column.id]
|
||||
) : (
|
||||
<IconButton
|
||||
onClick={(e) => {
|
||||
handleClick(e);
|
||||
setRowData(row);
|
||||
}}
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null)
|
||||
}
|
||||
|
||||
const isImage = (value: any) => {
|
||||
if (typeof value === "string") {
|
||||
return value.startsWith("http") || value.startsWith("data:image") // Check for URL or base64 image
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const handleDeleteButton = (id: string | undefined) => {
|
||||
if (!id) console.error("ID not found", id)
|
||||
|
||||
dispatch(deleteAdmin(id || ""))
|
||||
setDeleteModal(false) // Close the modal only after deletion
|
||||
handleClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<TableContainer component={Paper}>
|
||||
<Table sx={{ minWidth: 700 }} aria-label="customized table">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{columns.map((column) => (
|
||||
<StyledTableCell
|
||||
key={column.id}
|
||||
align={column.align || "left"}
|
||||
>
|
||||
{column.label}
|
||||
</StyledTableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rows.map((row, rowIndex) => (
|
||||
<StyledTableRow key={rowIndex}>
|
||||
{columns.map((column) => (
|
||||
<StyledTableCell
|
||||
key={column.id}
|
||||
align={column.align || "left"}
|
||||
>
|
||||
{isImage(row[column.id]) ? (
|
||||
<img
|
||||
src={row[column.id]}
|
||||
alt="Row "
|
||||
style={{
|
||||
width: "50px",
|
||||
height: "50px",
|
||||
objectFit: "cover",
|
||||
}}
|
||||
/>
|
||||
) : column.id !== "action" ? (
|
||||
row[column.id]
|
||||
) : (
|
||||
<IconButton
|
||||
onClick={(e) => {
|
||||
handleClick(e, row)
|
||||
setSelectedRow(row) // Store the selected row
|
||||
}}
|
||||
>
|
||||
<MoreVertRoundedIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
</StyledTableCell>
|
||||
))}
|
||||
</StyledTableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{open && (
|
||||
<Menu
|
||||
anchorEl={anchorEl}
|
||||
id="menu"
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
onClick={handleClose}
|
||||
transformOrigin={{ horizontal: "right", vertical: "top" }}
|
||||
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
|
||||
sx={{
|
||||
[`& .${listClasses.root}`]: {
|
||||
padding: "4px",
|
||||
},
|
||||
[`& .${paperClasses.root}`]: {
|
||||
padding: 0,
|
||||
},
|
||||
[`& .${dividerClasses.root}`]: {
|
||||
margin: "4px -4px",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "flex-start",
|
||||
}}
|
||||
>
|
||||
<MoreVertRoundedIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
</StyledTableCell>
|
||||
))}
|
||||
</StyledTableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{open && (
|
||||
<Menu
|
||||
anchorEl={anchorEl}
|
||||
id="menu"
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
onClick={handleClose}
|
||||
transformOrigin={{ horizontal: 'right', vertical: 'top' }}
|
||||
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
|
||||
sx={{
|
||||
[`& .${listClasses.root}`]: {
|
||||
padding: '4px',
|
||||
},
|
||||
[`& .${paperClasses.root}`]: {
|
||||
padding: 0,
|
||||
},
|
||||
[`& .${dividerClasses.root}`]: {
|
||||
margin: '4px -4px',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'flex-start',
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={() => setModalOpen(true)}
|
||||
color="primary"
|
||||
sx={{
|
||||
justifyContent: 'flex-start',
|
||||
py: 0,
|
||||
textTransform: 'capitalize',
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</Button>
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={() => setDeleteModal(true)}
|
||||
color="error"
|
||||
sx={{
|
||||
justifyContent: 'flex-start',
|
||||
py: 0,
|
||||
textTransform: 'capitalize',
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</Box>
|
||||
</Menu>
|
||||
)}
|
||||
</TableContainer>
|
||||
);
|
||||
};
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={() => setModalOpen(true)}
|
||||
color="primary"
|
||||
sx={{
|
||||
justifyContent: "flex-start",
|
||||
py: 0,
|
||||
textTransform: "capitalize",
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</Button>
|
||||
|
||||
export default CustomTable;
|
||||
<Button
|
||||
variant="text"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setDeleteModal(true)
|
||||
}}
|
||||
color="error"
|
||||
sx={{
|
||||
justifyContent: "flex-start",
|
||||
py: 0,
|
||||
textTransform: "capitalize",
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
{deleteModal && (
|
||||
<DeleteModal
|
||||
handleDelete={() =>
|
||||
handleDeleteButton(selectedRow?.id)
|
||||
}
|
||||
open={deleteModal}
|
||||
setDeleteModal={setDeleteModal}
|
||||
id={selectedRow?.id}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</Menu>
|
||||
)}
|
||||
</TableContainer>
|
||||
)
|
||||
}
|
||||
|
||||
export default CustomTable
|
||||
|
|
|
@ -1,77 +1,84 @@
|
|||
import { Box, Button, Modal, Typography } from '@mui/material';
|
||||
import { MouseEventHandler } from 'react';
|
||||
import { Box, Button, Modal, Typography } from "@mui/material"
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
setDeleteModal: Function;
|
||||
handleDelete: MouseEventHandler;
|
||||
};
|
||||
open: boolean
|
||||
setDeleteModal: Function
|
||||
handleDelete: (id: string | undefined) => void
|
||||
id?: string | undefined
|
||||
}
|
||||
|
||||
const style = {
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
width: 330,
|
||||
bgcolor: 'background.paper',
|
||||
borderRadius: 1.5,
|
||||
boxShadow: 24,
|
||||
p: 3,
|
||||
};
|
||||
position: "absolute",
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
width: 330,
|
||||
bgcolor: "background.paper",
|
||||
borderRadius: 1.5,
|
||||
boxShadow: 24,
|
||||
p: 3,
|
||||
}
|
||||
|
||||
const btnStyle = { py: 1, px: 5, width: '50%', textTransform: 'capitalize' };
|
||||
const btnStyle = { py: 1, px: 5, width: "50%", textTransform: "capitalize" }
|
||||
|
||||
export default function DeleteModal({
|
||||
open,
|
||||
setDeleteModal,
|
||||
handleDelete,
|
||||
open,
|
||||
setDeleteModal,
|
||||
handleDelete,
|
||||
id,
|
||||
}: Props) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
<Box sx={style}>
|
||||
<Typography
|
||||
id="modal-modal-title"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
align="center"
|
||||
// console.log("DeleteModal opened with ID:", id)
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
Delete Record
|
||||
</Typography>
|
||||
<Typography id="modal-modal-description" sx={{ mt: 2 }} align="center">
|
||||
Are you sure you want to delete this record?
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
mt: 4,
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="error"
|
||||
type="button"
|
||||
sx={btnStyle}
|
||||
onClick={() => setDeleteModal(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
type="button"
|
||||
color="primary"
|
||||
sx={btnStyle}
|
||||
onClick={handleDelete}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
<Box sx={style}>
|
||||
<Typography
|
||||
id="modal-modal-title"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
align="center"
|
||||
>
|
||||
Delete Record
|
||||
</Typography>
|
||||
<Typography
|
||||
id="modal-modal-description"
|
||||
sx={{ mt: 2 }}
|
||||
align="center"
|
||||
>
|
||||
Are you sure you want to delete this record?
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
mt: 4,
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
variant="contained"
|
||||
color="error"
|
||||
type="button"
|
||||
sx={btnStyle}
|
||||
onClick={() => setDeleteModal(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
type="button"
|
||||
color="primary"
|
||||
sx={btnStyle}
|
||||
onClick={() => handleDelete(id || "")}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
|
||||
import axios, { AxiosInstance } from 'axios';
|
||||
|
||||
// Axios instance for the production backend
|
||||
const backendHttp = axios.create({
|
||||
baseURL: process.env.REACT_APP_BACKEND_URL,
|
||||
});
|
||||
|
|
|
@ -3,12 +3,11 @@ import { Box, Button, Typography } from "@mui/material"
|
|||
import AddEditCategoryModal from "../../components/AddEditCategoryModal"
|
||||
import { useForm } from "react-hook-form"
|
||||
import CustomTable from "../../components/CustomTable"
|
||||
import DeleteModal from "../../components/Modals/DeleteModal/DeleteModal"
|
||||
// import DeleteModal from "../../components/Modals/DeleteModal/DeleteModal"
|
||||
import { useDispatch, useSelector } from "react-redux"
|
||||
import { adminList } from "../../redux/slices/authSlice"
|
||||
import { AppDispatch, RootState } from "../../redux/store/store" // Import RootState for selector
|
||||
|
||||
|
||||
// Sample data for categories
|
||||
|
||||
export default function AdminList() {
|
||||
|
@ -19,21 +18,16 @@ export default function AdminList() {
|
|||
const [deleteModal, setDeleteModal] = React.useState<boolean>(false)
|
||||
const [rowData, setRowData] = React.useState<any | null>(null)
|
||||
|
||||
const dispatch = useDispatch<AppDispatch>();
|
||||
const dispatch = useDispatch<AppDispatch>()
|
||||
|
||||
// Fetching admin data from the Redux store
|
||||
const admins = useSelector((state: RootState) => state.auth.admins);
|
||||
|
||||
|
||||
console.log(admins, "woihfiuwhfownfownefoi")
|
||||
|
||||
const admins = useSelector((state: RootState) => state.auth.admins)
|
||||
// Dispatching the API call when the component mounts
|
||||
useEffect(() => {
|
||||
dispatch(adminList());
|
||||
}, [dispatch]);
|
||||
|
||||
dispatch(adminList())
|
||||
}, [dispatch])
|
||||
|
||||
const handleClickOpen = () => {
|
||||
const handleClickOpen = () => {
|
||||
setModalOpen(true)
|
||||
setEditRow(null)
|
||||
}
|
||||
|
@ -43,9 +37,9 @@ export default function AdminList() {
|
|||
reset()
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
setDeleteModal(false)
|
||||
}
|
||||
// const handleDelete = () => {
|
||||
// setDeleteModal(false)
|
||||
// }
|
||||
|
||||
const categoryColumns = [
|
||||
{ id: "srno", label: "Sr No" },
|
||||
|
@ -55,11 +49,19 @@ export default function AdminList() {
|
|||
]
|
||||
|
||||
// If no admins are available, display the sample data
|
||||
const categoryRows = admins?.length ? admins?.map((admin: { name: any; role: any }, index: number) => ({
|
||||
srno: index + 1,
|
||||
name: admin?.name,
|
||||
role: admin.role,
|
||||
})) : []
|
||||
const categoryRows = admins?.length
|
||||
? admins?.map(
|
||||
(
|
||||
admin: { id: string; name: string; role: string },
|
||||
index: number
|
||||
) => ({
|
||||
id: admin.id,
|
||||
srno: index + 1,
|
||||
name: admin?.name,
|
||||
role: admin.role,
|
||||
})
|
||||
)
|
||||
: []
|
||||
|
||||
return (
|
||||
<>
|
||||
|
@ -97,6 +99,7 @@ export default function AdminList() {
|
|||
rows={categoryRows}
|
||||
editRow={editRow}
|
||||
setDeleteModal={setDeleteModal}
|
||||
deleteModal={deleteModal}
|
||||
setRowData={setRowData}
|
||||
setModalOpen={setModalOpen}
|
||||
/>
|
||||
|
@ -105,11 +108,11 @@ export default function AdminList() {
|
|||
handleClose={handleCloseModal}
|
||||
editRow={rowData}
|
||||
/>
|
||||
<DeleteModal
|
||||
{/* <DeleteModal
|
||||
open={deleteModal}
|
||||
setDeleteModal={setDeleteModal}
|
||||
handleDelete={handleDelete}
|
||||
/>
|
||||
/> */}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
|
@ -1,26 +1,36 @@
|
|||
import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit"
|
||||
import {
|
||||
createSlice,
|
||||
createAsyncThunk,
|
||||
PayloadAction,
|
||||
isRejectedWithValue,
|
||||
} from "@reduxjs/toolkit"
|
||||
import axios from "axios"
|
||||
import { backendHttp, apiHttp } from "../../lib/https"
|
||||
import { toast } from "react-toastify"
|
||||
|
||||
// Define types for state
|
||||
interface User {
|
||||
map(arg0: (admin: { name: any; role: any }, index: number) => { srno: number; name: any; role: any }): unknown
|
||||
map(
|
||||
arg0: (
|
||||
admin: { name: any; role: any },
|
||||
index: number
|
||||
) => { srno: number; name: any; role: any }
|
||||
): unknown
|
||||
id: string
|
||||
email: string
|
||||
}
|
||||
|
||||
interface Admin {
|
||||
id: string,
|
||||
name: string,
|
||||
id: string
|
||||
name: string
|
||||
role: string
|
||||
}
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
admins: Admin[];
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
user: User | null
|
||||
admins: Admin[]
|
||||
isAuthenticated: boolean
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
}
|
||||
|
||||
// Async thunk for login
|
||||
|
@ -30,7 +40,10 @@ export const loginUser = createAsyncThunk<
|
|||
{ rejectValue: string }
|
||||
>("auth/login", async ({ email, password }, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await backendHttp.post("admin/login", { email, password })
|
||||
const response = await backendHttp.post("admin/login", {
|
||||
email,
|
||||
password,
|
||||
})
|
||||
localStorage.setItem("authToken", response.data?.data?.token) // Save token
|
||||
toast.success(response.data?.message)
|
||||
return response.data
|
||||
|
@ -66,19 +79,56 @@ export const adminList = createAsyncThunk<
|
|||
{ rejectValue: string }
|
||||
>("/auth", async (_, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await apiHttp.get("/auth");
|
||||
console.log(response)
|
||||
return response?.data?.data?.map((admin: { name: string; role: string }) => ({
|
||||
|
||||
name: admin?.name,
|
||||
role: admin?.role || "N/A",
|
||||
}));
|
||||
const response = await apiHttp.get("/auth")
|
||||
console.log(response?.data?.data)
|
||||
return response?.data?.data?.map(
|
||||
(admin: { id: string; name: string; role: string }) => ({
|
||||
id: admin.id,
|
||||
name: admin?.name,
|
||||
role: admin?.role || "N/A",
|
||||
})
|
||||
)
|
||||
console.log(response.data.data)
|
||||
} catch (error: any) {
|
||||
return rejectWithValue(error.response?.data?.message || "An error occurred");
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
)
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
export const deleteAdmin = createAsyncThunk<
|
||||
string,
|
||||
string,
|
||||
{ rejectValue: string }
|
||||
>("deleteAdmin", async (id, { rejectWithValue }) => {
|
||||
try {
|
||||
const response = await apiHttp.delete(`/auth/${id}`)
|
||||
// console.log(response, "response of deletion")
|
||||
return id // Returning the deleted admin's ID
|
||||
} catch (error: any) {
|
||||
return rejectWithValue(
|
||||
error.response?.data?.message || "An error occurred"
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
// export const putAdmin = createAsyncThunk<
|
||||
// Admin, // Return type (updated admin object)
|
||||
// { id: string; data: Partial<Admin> }, // Argument type
|
||||
// { rejectValue: string } // Rejection type
|
||||
// >(
|
||||
// "updateAdmin",
|
||||
// async ({ id, data }, { rejectWithValue }) => {
|
||||
// try {
|
||||
// const response = await apiHttp.put(`/auth/${id}`, data)
|
||||
// return response.data // Ensure response contains the updated admin object
|
||||
// } catch (error: any) {
|
||||
// return rejectWithValue(
|
||||
// error.response?.data?.message || "An error occurred"
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
// )
|
||||
|
||||
const initialState: AuthState = {
|
||||
user: null,
|
||||
|
@ -86,7 +136,7 @@ const initialState: AuthState = {
|
|||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
const authSlice = createSlice({
|
||||
name: "auth",
|
||||
|
@ -140,16 +190,19 @@ const authSlice = createSlice({
|
|||
}
|
||||
)
|
||||
|
||||
// created by Jaanvi and Eknoor
|
||||
.addCase(adminList.pending, (state) => {
|
||||
// created by Jaanvi and Eknoor
|
||||
//AdminList
|
||||
.addCase(adminList.pending, (state) => {
|
||||
state.isLoading = true
|
||||
state.error = null
|
||||
})
|
||||
.addCase(adminList.fulfilled, (state, action: PayloadAction<Admin[]>) => {
|
||||
state.isLoading = false;
|
||||
state.admins = action.payload; // ✅ Store admins correctly
|
||||
})
|
||||
|
||||
.addCase(
|
||||
adminList.fulfilled,
|
||||
(state, action: PayloadAction<Admin[]>) => {
|
||||
state.isLoading = false
|
||||
state.admins = action.payload
|
||||
}
|
||||
)
|
||||
|
||||
.addCase(
|
||||
adminList.rejected,
|
||||
|
@ -158,6 +211,37 @@ const authSlice = createSlice({
|
|||
state.error = action.payload || "An error occurred"
|
||||
}
|
||||
)
|
||||
|
||||
.addCase(deleteAdmin.pending, (state) => {
|
||||
state.isLoading = true
|
||||
})
|
||||
.addCase(deleteAdmin.fulfilled, (state, action) => {
|
||||
state.isLoading = false
|
||||
state.admins = state.admins.filter(
|
||||
(admin) => String(admin.id) !== String(action.payload)
|
||||
)
|
||||
})
|
||||
.addCase(deleteAdmin.rejected, (state, action) => {
|
||||
state.isLoading = false
|
||||
state.error = action.payload || "Failed to delete admin"
|
||||
})
|
||||
//update Admin
|
||||
|
||||
// .addCase(putAdmin.pending, (state) => {
|
||||
// state.isLoading = true
|
||||
// state.error = null
|
||||
// })
|
||||
// .addCase(putAdmin.fulfilled, (state, action: PayloadAction<Admin>) => {
|
||||
// state.isLoading = false
|
||||
// state.admins = state.admins.map((admin) =>
|
||||
// admin.id === action.payload.id ? action.payload : admin
|
||||
// )
|
||||
// })
|
||||
// .addCase(putAdmin.rejected, (state, action: PayloadAction<string | undefined>) => {
|
||||
// state.isLoading = false
|
||||
// state.error = action.payload || "Failed to update admin"
|
||||
// })
|
||||
|
||||
},
|
||||
})
|
||||
|
||||
|
|
Loading…
Reference in a new issue