feat: add input of long url on homepage
This commit is contained in:
6
src/features/url/types.ts
Normal file
6
src/features/url/types.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
|
||||
export interface UrlState {
|
||||
shortUrl: string;
|
||||
status: 'idle' | 'loading' | 'succeeded' | 'failed';
|
||||
error: string | null;
|
||||
}
|
||||
53
src/features/url/urlSlice.ts
Normal file
53
src/features/url/urlSlice.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
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<string>) => {
|
||||
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;
|
||||
Reference in New Issue
Block a user