Skip to content
Snippets Groups Projects
user.fetch.ts 999 B
Newer Older
  • Learn to ignore specific revisions
  • import { createAsyncThunk } from "@reduxjs/toolkit"
    import { setUser } from "@shared/reducer/user.reducer"
    import { RootState } from "src/stores"
    import { api, UserServiceGetUsersApiArg } from "./api"
    
    export const fetchUser = createAsyncThunk('user/fetchUser', (_, thunkAPI) => {
        const payload: UserServiceGetUsersApiArg = {}
    
        thunkAPI.dispatch(api.endpoints.userServiceGetUsers.initiate(payload)).then((response) => {
            if (response.error || !response.data?.user?.length) {
                // TODO proper error handling
                throw new Error('Fetching the pnd list after successful login failed')
            }
    
            const { user } = thunkAPI.getState() as RootState
            const matchedUser = response.data.user.find((_user) => _user.name === user.username)
    
            if (!matchedUser) {
    
                // TODO proper error handling => logout
    
                throw new Error('No user found with the provided username')
            }
    
            thunkAPI.dispatch(setUser(matchedUser))
        })
    })