fetcing apiSlice

parent 15c2b0eb
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
interface Organization {
id: number | string;
id: number;
bin: string;
organization_code: string;
organization_name: string;
status: string;
code: string;
name: string;
status: number;
created: string;
deleted: null;
login: string;
password: string;
host: string;
}
export const apiSlice = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: "https://669f8d88b132e2c136fe5106.mockapi.io/api/v1" }),
tagTypes: ["organizations"], // Определяет типы тегов для инвалидации кэша или инвалидации данных, связанных с конкретными запросами или мутациями.
baseQuery: fetchBaseQuery({
baseUrl: "/esutd/api/organizations",
prepareHeaders: (headers, { getState }) => {
const accessToken = `OTA3MTEzNzctYzA3YS00NzRkLTkyNDgtNzk4ZmEzMzViNzlj`;
if (accessToken) {
headers.set("Authorization", `Bearer Token ${accessToken}`);
}
headers.set("Accept", "*/*");
return headers;
},
}),
tagTypes: ["organizations"],
endpoints: (builder) => ({
getOrganizations: builder.query<Organization[], void>({
query: () => '/organizations',
providesTags: ["organizations"], // Определяет теги, которые будут инвалидированы при получении данных, чтобы обновить кэш, связанный с этими данными.
query: () => '/list',
providesTags: ["organizations"],
}),
getOrganization: builder.query<Organization, string>({
query: (orgId) => `/organizations/${orgId}`,
query: (orgId) => `/info?id=${orgId}`,
}),
addNewOrganization: builder.mutation<Organization, Partial<Organization>>({
query: (initialOrg) => ({
url: '/organizations',
url: '/add',
method: 'POST',
body: initialOrg,
}),
invalidatesTags: ["organizations"], // при успешном выполнении этой мутации необходимо инвалидировать теги, связанные с организациями, чтобы обновить кэш.
invalidatesTags: ["organizations"],
}),
editOrganization: builder.mutation<Organization, Partial<Organization>>({
query: ({ id, ...rest }) => ({
url: `/organizations/${id}`,
url: `/edit?id=${id}`,
method: 'PUT',
body: rest,
}),
......@@ -38,7 +56,7 @@ export const apiSlice = createApi({
}),
deleteOrganization: builder.mutation<{ success: boolean; id: number }, number>({
query: (orgId) => ({
url: `/organizations/${orgId}`,
url: `/delete?id=${orgId}`,
method: 'DELETE',
}),
invalidatesTags: ["organizations"],
......
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import { Provider } from 'react-redux';
import './index.css'
import './index.css';
import store from '../src/store/store.ts';
ReactDOM.createRoot(document.getElementById('root')!).render(
......@@ -11,4 +11,4 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
<App />
</Provider>
</React.StrictMode>,
)
);
import React, { useState } from 'react';
import { useNavigate } from 'react-router';
import { MaterialSymbol } from 'react-material-symbols';
import { Button, Space, Tag, Modal, message } from 'antd';
import type { TableProps } from 'antd';
import './Homepage.css';
import { useDeleteOrganizationMutation } from '../../features/api/apiSlice';
export interface DataType {
id: string | number;
id: number;
bin: string;
organization_code: string;
organization_name: string;
status: string;
code: string;
name: string;
status: number;
host: string;
}
const getStatusText = (status: number) => {
switch (status) {
case 0: return "удален";
case 1: return "заблокирован";
case 2: return "активен";
default: return "неизвестно";
}
}
const getStatusColor = (status: number) => {
switch (status) {
case 0: return 'red';
case 1: return 'orange';
case 2: return 'green';
default: return 'grey';
}
}
export const columns: TableProps<DataType>['columns'] = [
{
title: "ID",
......@@ -28,12 +44,12 @@ export const columns: TableProps<DataType>['columns'] = [
},
{
title: "Код организации",
dataIndex: "organization_code",
dataIndex: "code",
key: "code"
},
{
title: "Наименование организации",
dataIndex: "organization_name",
dataIndex: "name",
key: "name"
},
{
......@@ -45,16 +61,11 @@ export const columns: TableProps<DataType>['columns'] = [
title: "Статус",
dataIndex: "status",
key: "status",
render: (_, record) => {
const color = record.status === '0' ? 'red' : record.status === '1' ? 'processing' : 'green';
return (
<p>
<Tag color={color} style={{ fontSize: '14px' }}>
{record.status === '0' ? 'удален' : record.status === '1' ? 'заблокирован' : 'активен'}
</Tag>
</p>
)
}
render: (_, record) => (
<Tag color={getStatusColor(record.status)} style={{ fontSize: '14px' }}>
{getStatusText(record.status)}
</Tag>
)
},
{
title: "Действия",
......@@ -78,7 +89,7 @@ export const ActionColumn: React.FC<{ data: DataType }> = ({ data }) => {
const handleDeleteModalOk = async () => {
try {
await deleteOrganization(Number(data.id)).unwrap();
await deleteOrganization(data.id).unwrap();
message.success('Организация успешно удалена!');
setOpen(false);
} catch (err) {
......@@ -91,16 +102,16 @@ export const ActionColumn: React.FC<{ data: DataType }> = ({ data }) => {
};
const handleEditClick = () => {
navigate(`/edit/${data.id.toString()}`);
navigate(`/edit/${data.id}`);
}
return (
<Space>
<Button onClick={handleEditClick} icon={<MaterialSymbol icon='visibility' size={22} />} />
<Button onClick={showDeleteModal} icon={<MaterialSymbol icon='delete' size={22} />} />
<Button onClick={handleEditClick} />
<Button onClick={showDeleteModal} />
<Modal
open={open}
title={`Вы уверены в том, что хотите удалить ${data.organization_name}?`}
title={`Вы уверены в том, что хотите удалить ${data.name}?`}
footer={() => (
<div style={{ textAlign: 'start', marginTop: '1rem' }}>
<Button key="submit" type="primary" danger onClick={handleDeleteModalOk} style={{ marginRight: '.5rem' }}>
......@@ -114,4 +125,4 @@ export const ActionColumn: React.FC<{ data: DataType }> = ({ data }) => {
/>
</Space>
)
}
\ No newline at end of file
}
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router';
import { useSelector, useDispatch } from 'react-redux';
import { MaterialSymbol } from 'react-material-symbols';
import { Button, Pagination, Spin, Table } from 'antd';
import { useGetOrganizationsQuery, } from '../../features/api/apiSlice';
import { useGetOrganizationsQuery } from '../../features/api/apiSlice';
import { setCurrentPage, setTotalOrgNumber } from '../../features/pagination/mainPagination';
import { DataType, columns } from './Columns';
import './Homepage.css';
......@@ -42,7 +41,16 @@ const HomePage: React.FC = () => {
if (isLoading) {
table = <Spin />
} else if (isSuccess) {
const dataSource = orgs.map((org) => ({ ...org, key: org.id }));
const dataSource = orgs.map((org) => ({
id: org.id,
bin: org.bin,
code: org.code,
name: org.name,
host: org.host,
status: org.status,
key: org.id
}));
table = <Table dataSource={paginatedData(dataSource)} columns={columns} pagination={false} />
} else if (isError) {
table = <div>{error.toString()}</div>
......@@ -58,7 +66,7 @@ const HomePage: React.FC = () => {
<div className="container">
<section className='section'>
<div className="add">
<Button icon={<MaterialSymbol icon='add_circle' size={20} color='#0E2B52' />} className='add_title' onClick={handleAddClick}>
<Button className='add_title' onClick={handleAddClick}>
Добавить
</Button>
</div>
......
......@@ -9,6 +9,6 @@ const store: Store = configureStore({
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
})
});
export default store;
\ No newline at end of file
export default store;
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
server: {
proxy: {
'/api': {
target: 'http://77.243.80.217:8080',
changeOrigin: true,
// rewrite: (path) => path.replace(/^\/api/, ''),
secure: false,
}
}
}
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment