bodyPartSlice.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
  2. import { fetchBodyParts, BodyPart, BodyPartParams } from '../API/bodyPart';
  3. import { AxiosError } from 'axios';
  4. import { setCurrentPatientType } from './patientTypeSlice';
  5. interface BodyPartState {
  6. items: BodyPart[];
  7. loading: boolean;
  8. error: string | null;
  9. byPatientType: BodyPart[];
  10. }
  11. const initialState: BodyPartState = {
  12. items: [],
  13. loading: false,
  14. error: null,
  15. byPatientType: [],
  16. };
  17. export const getBodyParts = createAsyncThunk(
  18. 'bodyPart/getBodyParts',
  19. async (
  20. { params, token }: { params: BodyPartParams; token: string },
  21. { rejectWithValue }
  22. ) => {
  23. try {
  24. const data = await fetchBodyParts(params, token);
  25. return data;
  26. } catch (err: unknown) {
  27. let errorMessage = 'Failed to fetch body parts';
  28. console.log(errorMessage);
  29. if (
  30. err &&
  31. typeof err === 'object' &&
  32. 'message' in err &&
  33. typeof (err as AxiosError).message === 'string'
  34. ) {
  35. errorMessage = (err as AxiosError).message;
  36. }
  37. return rejectWithValue(errorMessage);
  38. }
  39. }
  40. );
  41. const bodyPartSlice = createSlice({
  42. name: 'bodyPart',
  43. initialState,
  44. reducers: {
  45. // setBodyPartsByPatientType: (state, action: PayloadAction<{ patientTypeId: string }>) => {
  46. // // state.byPatientType[action.payload.patientTypeId] = action.payload.bodyParts;
  47. // },
  48. },
  49. extraReducers: (builder) => {
  50. builder
  51. .addCase(setCurrentPatientType, (state, action) => {
  52. console.log(
  53. '当前 patient type 变化-- bodyPart接收到信号:',
  54. action.payload
  55. );
  56. if (action.payload) {
  57. const patientTypeId = action.payload.patient_type_id;
  58. console.log(
  59. '基于 patient type过滤 bodyPart byPatientType:',
  60. patientTypeId
  61. );
  62. state.byPatientType = state.items.filter(
  63. (item) => item.patient_type === patientTypeId
  64. );
  65. console.log('过滤后的 bodyPart byPatientType:', state.byPatientType);
  66. }
  67. })
  68. .addCase(getBodyParts.pending, (state) => {
  69. state.loading = true;
  70. state.error = null;
  71. })
  72. .addCase(getBodyParts.fulfilled, (state, action) => {
  73. state.loading = false;
  74. state.items = action.payload;
  75. })
  76. .addCase(getBodyParts.rejected, (state, action) => {
  77. state.loading = false;
  78. state.error = action.payload as string;
  79. });
  80. },
  81. });
  82. export default bodyPartSlice.reducer;