Commit 23c5d165 authored by bekzat kapan's avatar bekzat kapan

#7 Создал файл requestSlice и написал в нем логику передачи данных в Api

parent e04e5a9f
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axiosClient from '@/helpers/axiosClient';
interface RequestState {
loading: boolean;
error?: string | null;
result: string;
}
interface IData {
password: string;
message: string;
}
const initialState: RequestState = {
loading: false,
error: null,
result: '',
};
export const encodeMessage = createAsyncThunk(
'request/encode',
async (data: IData) => {
try {
const response = await axiosClient.post('/encode', data);
return response.data.encoded;
} catch (error: any) {
throw new Error(
error.response?.data?.message || 'Error encoding message'
);
}
}
);
export const decodeMessage = createAsyncThunk(
'request/decode',
async (data: IData) => {
try {
const response = await axiosClient.post('/decode', data);
return response.data.decoded;
} catch (error: any) {
throw new Error(
error.response?.data?.message || 'Error decoding message'
);
}
}
);
const requestSlice = createSlice({
name: 'request',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(encodeMessage.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(encodeMessage.fulfilled, (state, action) => {
state.loading = false;
state.result = action.payload;
})
.addCase(encodeMessage.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || "Error occured";
})
.addCase(decodeMessage.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(encodeMessage.fulfilled, (state, action) => {
state.loading = false;
state.result = action.payload;
})
.addCase(encodeMessage.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || "Error occured";
});
},
});
export default requestSlice.reducer;
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