Skip to content
Snippets Groups Projects
user.routine.ts 1.46 KiB
Newer Older
  • Learn to ignore specific revisions
  • Matthias Feyll's avatar
    Matthias Feyll committed
    import { api, PndServiceGetPndListApiArg, UserServiceGetUsersApiArg } from "@api/api"
    import { setPnds } from "@component/devices/reducer/device.reducer"
    import { createAsyncThunk } from "@reduxjs/toolkit"
    import { setUser } from "@shared/reducer/user.reducer"
    import { RootState } from "src/stores"
    
    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))
        })
    })
    
    export const fetchPnds = createAsyncThunk('device/fetchPnds', (_, thunkApi) => {
        const payload: PndServiceGetPndListApiArg = {
            timestamp: new Date().getTime().toString(),
        }
    
        const subscription = thunkApi.dispatch(api.endpoints.pndServiceGetPndList.initiate(payload))
        subscription.unwrap().then((response) => {
            thunkApi.dispatch(setPnds(response.pnd))
        })
    })