为GET和POST请求分离redux状态状态

时间:2020-10-29 13:42:59

标签: reactjs redux logic redux-toolkit

我使用Redux来管理应用程序中合作伙伴的状态,最近我尝试规范化数据并破坏了所有内容。该状态有一个status,它同时响应我的API GET和POST请求。我看到这是不正确的:如果我的POST请求失败,它将状态更改为“失败”,并且依赖于此状态来显示GET请求中的信息的所有组件都将显示错误消息。有最佳实践吗?

//the initialPartner is an object: { name: "Partner1" }

import {
    createSlice, 
    createAsyncThunk,
    createEntityAdapter
} from '@reduxjs/toolkit'
import axios from 'axios'

import { ADD_PARTNER_CONFIG, SERVER } from '../../app/constants'

const partnerAdapter = createEntityAdapter();

const initialState = partnerAdapter.getInitialState({
    status: 'idle',
    error: null
});

export const fetchPartners = createAsyncThunk(
    'partners/fetchPartners',
    async () => {
        const response = await axios.get(`${SERVER}/rest/partners`)
        return response.data
    }
)

export const addNewPartner = createAsyncThunk(
    'partners/addNewPartner',
    async initialPartner => {
        const response = await axios(ADD_PARTNER_CONFIG, initialPartner)
        return response.data
    }
)

const partnerSlice = createSlice({
    name: 'partners',
    initialState,
    extraReducers:{
        [fetchPartners.pending]: (state, action) => {
            state.status = 'loading';
        },
        [fetchPartners.fulfilled]: (state, action) => {
            state.status = 'succeeded';
            partnerAdapter.upsertMany(state, action.payload);
        },
        [fetchPartners.rejected]: (state, action) => {
            state.status = 'failed';
            state.error = action.error.message;
        },
        [addNewPartner.fulfilled]: partnerAdapter.addOne,
        [addNewPartner.rejected]: (state, action) => {
            state.status = 'failed';
            state.error = action.error.message;
        }
    }
})

export default partnerSlice.reducer

export const { partnerAdded } = partnerSlice.actions


export const {
    selectAll: selectAllPartners,
    selectById: selectPartnerById,
    selectIds: selectPartnerIds
} = partnerAdapter.getSelectors(state => state.partners)

0 个答案:

没有答案