123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
- import { fetchBodyParts, BodyPart, BodyPartParams } from '../API/bodyPart';
- import { AxiosError } from 'axios';
- import { setCurrentPatientType } from './patientTypeSlice';
- interface BodyPartState {
- items: BodyPart[];
- loading: boolean;
- error: string | null;
- byPatientType: BodyPart[];
- current: BodyPart | null;
- }
- const initialState: BodyPartState = {
- items: [],
- loading: false,
- error: null,
- byPatientType: [],
- current: null,
- };
- export const getBodyParts = createAsyncThunk(
- 'bodyPart/getBodyParts',
- async ({ params }: { params: BodyPartParams }, { rejectWithValue }) => {
- try {
- const data = await fetchBodyParts(params);
- return data;
- } catch (err: unknown) {
- let errorMessage = 'Failed to fetch body parts';
- console.log(errorMessage);
- if (
- err &&
- typeof err === 'object' &&
- 'message' in err &&
- typeof (err as AxiosError).message === 'string'
- ) {
- errorMessage = (err as AxiosError).message;
- }
- return rejectWithValue(errorMessage);
- }
- }
- );
- const bodyPartSlice = createSlice({
- name: 'bodyPart',
- initialState,
- reducers: {
- setCurrentBodyPart: (state, action: PayloadAction<BodyPart | null>) => {
- if (action.payload) {
- state.current =
- state.byPatientType.find(
- (item) => item.body_part_id === action.payload?.body_part_id
- ) || null;
- } else {
- state.current = null;
- }
- },
- // setBodyPartsByPatientType: (state, action: PayloadAction<{ patientTypeId: string }>) => {
- // // state.byPatientType[action.payload.patientTypeId] = action.payload.bodyParts;
- // },
- },
- extraReducers: (builder) => {
- builder
- .addCase(setCurrentPatientType, (state, action) => {
- console.log(
- '当前 patient type 变化-- bodyPart接收到信号:',
- action.payload
- );
- if (action.payload) {
- const patientTypeId = action.payload.patient_type_id;
- console.log(
- '基于 patient type过滤 bodyPart byPatientType:',
- patientTypeId
- );
- state.byPatientType = state.items.filter(
- (item) => item.patient_type === patientTypeId
- );
- console.log('过滤后的 bodyPart byPatientType:', state.byPatientType);
- }
- })
- .addCase(getBodyParts.pending, (state) => {
- state.loading = true;
- state.error = null;
- })
- .addCase(getBodyParts.fulfilled, (state, action) => {
- state.loading = false;
- state.items = action.payload;
- })
- .addCase(getBodyParts.rejected, (state, action) => {
- state.loading = false;
- state.error = action.payload as string;
- });
- },
- });
- export const { setCurrentBodyPart } = bodyPartSlice.actions;
- export default bodyPartSlice.reducer;
|