candidat
/
mag
80 строк · 2.5 Кб
1import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
2import Tokens from './api/tokensApi';
3import AuthApi from './api/userApi';
4import type { User, UserWithoutIdwithPassword, UserWithoutName } from './types/userTypes';
5
6type StateAuth = {
7user: User | undefined;
8accessToken: string | undefined;
9error: string | undefined;
10loading: boolean;
11};
12
13const initialState: StateAuth = {
14user: undefined,
15accessToken: undefined,
16error: undefined,
17loading: true,
18};
19
20export const registrationThunk = createAsyncThunk(
21'registration/user',
22(body: UserWithoutIdwithPassword) => AuthApi.registartion(body),
23);
24export const refreshTokens = createAsyncThunk('refreshTokens/user', () => Tokens.refreshTokens());
25export const logoutThunk = createAsyncThunk('logout/user', () => AuthApi.logout());
26export const authorizationThunk = createAsyncThunk('authorization/user', (body: UserWithoutName) =>
27AuthApi.authrozation(body),
28);
29
30const authSlice = createSlice({
31name: 'auth',
32initialState,
33reducers: {},
34extraReducers: (builder) => {
35builder
36.addCase(registrationThunk.fulfilled, (state, action) => {
37state.user = action.payload.user;
38state.accessToken = action.payload.accessToken;
39state.loading = false;
40state.error = undefined;
41})
42.addCase(registrationThunk.pending, (state) => {
43state.loading = true;
44})
45.addCase(registrationThunk.rejected, (state, action) => {
46state.error = action.error.message;
47state.loading = false;
48})
49.addCase(refreshTokens.fulfilled, (state, action) => {
50state.user = action.payload.user;
51state.accessToken = action.payload.accessToken;
52})
53.addCase(refreshTokens.pending, (state) => {
54state.loading = true;
55})
56.addCase(refreshTokens.rejected, (state, action) => {
57state.error = action.error.message;
58state.loading = false;
59})
60.addCase(authorizationThunk.fulfilled, (state, action) => {
61state.user = action.payload.user;
62state.accessToken = action.payload.accessToken;
63state.loading = false;
64state.error = undefined;
65})
66.addCase(authorizationThunk.pending, (state) => {
67state.loading = true;
68})
69.addCase(authorizationThunk.rejected, (state, action) => {
70state.error = action.error.message;
71state.loading = false;
72})
73.addCase(logoutThunk.fulfilled, (state) => {
74state.user = undefined;
75state.accessToken = undefined;
76});
77},
78});
79
80export default authSlice;
81