feat: added redux & ducks

This commit is contained in:
Home
2025-10-11 00:20:28 +03:00
parent de6f4bc6f9
commit 45c21cca82
43 changed files with 500 additions and 77 deletions

View File

@@ -0,0 +1,30 @@
import { serversSlice } from './slice';
import { getServers } from './api';
import { createAsyncThunk } from '@reduxjs/toolkit';
import { getServersState } from './selectors';
import type { RootState } from '../../../store';
const PREFFIX = 'servers'
export const fetchServers = createAsyncThunk(
`${PREFFIX}/fetchAll`,
async (_, { dispatch, getState }) => {
const { loading } = getServersState(getState() as RootState);
try {
if (loading) {
return;
}
dispatch(serversSlice.actions.setLoading(true));
const response = await getServers().then(({ data }) => data);
dispatch(serversSlice.actions.setServers(response));
} catch (e) {
const message =
e instanceof Error ? e.message : `Unknown error in ${PREFFIX}/fetchAll`;
dispatch(serversSlice.actions.setError(message));
} finally {
dispatch(serversSlice.actions.setLoading(false));
}
},
);

View File

@@ -0,0 +1,5 @@
import type { AxiosResponse } from 'axios';
import { api } from '../../../api/api';
import type { ServerDTO } from './dto';
export const getServers = () => api.get<never, AxiosResponse<ServerDTO[]>>('/servers');

View File

@@ -0,0 +1,7 @@
export interface ServerDTO {
id: number | string
name: string
hostname: string
grpc_port: number
status: string
}

View File

@@ -0,0 +1,4 @@
export * from './actions'
export * from './dto'
export * from './slice'
export * from './selectors'

View File

@@ -0,0 +1,3 @@
import type { RootState } from '../../../store';
export const getServersState = (state: RootState) => state.servers;

View File

@@ -0,0 +1,32 @@
import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { ServerDTO } from './dto';
export interface ServersState {
loading: boolean;
servers: ServerDTO[];
error: null | string;
}
const initialState: ServersState = {
loading: false,
servers: [],
error: null,
};
export const serversSlice = createSlice({
name: 'servers',
initialState,
reducers: {
setLoading: (state, action: PayloadAction<boolean>) => {
state.loading = action.payload
},
setServers: (state, action: PayloadAction<ServerDTO[]>) => {
state.servers = action.payload
},
setError: (state, action: PayloadAction<string>) => {
state.error = action.payload
}
},
});