来自一个redux-toolkit形实转换的多个操作

w8f9ii69  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(177)

工具包,我试图确切地理解createAsyncThunk是如何适应这一切的。我想对我的服务器进行一次调用,以在一次调用中获得会话信息和用户信息。然而,从我到目前为止在createAsyncThunk上看到的情况来看,它只使用了一个状态切片?有人能详细说明一下我如何同时访问会话和用户吗?下面是一个示例来说明。

const payload = await myApi.login(loginInfo)
dispatch(loginSession(payload.session)
dispatch(loginUser(payload.user)

export const sessionSlice = createSlice({
    name:'session',
    initialState,
    reducers: {
        loginSession: (state,action:PayloadAction<schema.Session>) => {

            state = action.payload
         },
    },
})

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        loginUser:(state,action:PayloadAction<schema.User>) => {
            if (state !== null) {
                throw new Error('a user is already logged in')
            }
            state = action.payload
        },
    }
})
xa9qqrwz

xa9qqrwz1#

const payload = await myApi.login(loginInfo)
dispatch(loginFulfilled({ 
  session: payload.session,
  user: payload.user,
})

export const sessionSlice = createSlice({
    name:'session',
    initialState,
    reducers: {
        loginFulfilled: (state,action:PayloadAction<{session: schema.Session}>) => {

            state = action.payload.session
         },
    },
})

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        loginFulfilled:(state,action:PayloadAction<{user: schema.User>}) => {
            if (state !== null) {
                throw new Error('a user is already logged in')
            }
            state = action.payload.user
        },
    }
})

相关问题