import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit' import { RootState } from '../../app/store'; import { shortenUrlApi } from '../../api/url/urlApi'; import { UrlState } from './types'; export const shortenUrl = createAsyncThunk( 'url/shortenUrl', async (longUrl: string) => { const data = await shortenUrlApi({ longUrl }); return `https://minxa.lol/${data.shortCode}`; } ); const initialState: UrlState = { shortUrl: '', status: 'idle', error: null, }; const urlSlice = createSlice({ name: 'url', initialState, reducers: { clearShortUrl(state) { state.shortUrl = ''; state.status = 'idle'; state.error = null; }, }, extraReducers: (builder) => { builder .addCase(shortenUrl.pending, (state) => { state.status = 'loading'; state.shortUrl = ''; state.error = null; }) .addCase(shortenUrl.fulfilled, (state, action: PayloadAction) => { state.status = 'succeeded'; state.shortUrl = action.payload; }) .addCase(shortenUrl.rejected, (state, action) => { state.status = 'failed'; state.error = action.error.message || 'Something went wrong'; }); }, }); export const { clearShortUrl } = urlSlice.actions; export const selectShortUrl = (state: RootState) => state.url.shortUrl; export const selectUrlStatus = (state: RootState) => state.url.status; export const selectUrlError = (state: RootState) => state.url.error; export default urlSlice.reducer;