patientTypeSlice.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import {
  2. createSlice,
  3. createAsyncThunk,
  4. createAction,
  5. PayloadAction,
  6. } from '@reduxjs/toolkit';
  7. import { fetchPatientTypes, PatientType } from '../API/patientType';
  8. import { AxiosError } from 'axios';
  9. interface PatientTypeState {
  10. items: PatientType[];
  11. loading: boolean;
  12. error: string | null;
  13. current: PatientType | null;
  14. }
  15. const initialState: PatientTypeState = {
  16. items: [],
  17. loading: false,
  18. error: null,
  19. current: null,
  20. };
  21. export const setCurrentPatientType = createAction<PatientType | null>(
  22. 'patientType/setCurrentPatientType'
  23. );
  24. export const patientTypeChanged = createAction<PatientType | null>(
  25. 'patientType/patientTypeChanged'
  26. );
  27. export const getPatientTypes = createAsyncThunk(
  28. 'patientType/getPatientTypes',
  29. async (_, { rejectWithValue }) => {
  30. try {
  31. console.log('Fetching patient types with params:');
  32. const data = await fetchPatientTypes();
  33. return data;
  34. } catch (err: unknown) {
  35. let errorMessage = 'Failed to fetch patient types';
  36. if (
  37. err &&
  38. typeof err === 'object' &&
  39. 'message' in err &&
  40. typeof (err as AxiosError).message === 'string'
  41. ) {
  42. errorMessage = (err as AxiosError).message;
  43. }
  44. return rejectWithValue(errorMessage);
  45. }
  46. }
  47. );
  48. const patientTypeSlice = createSlice({
  49. name: 'patientType',
  50. initialState,
  51. reducers: {
  52. setCurrentPatientType: (
  53. state,
  54. action: PayloadAction<PatientType | null>
  55. ) => {
  56. console.log('当前 patient type 变化:', action.payload);
  57. state.current = action.payload;
  58. if (action.payload) {
  59. // const patientTypeId = action.payload.patient_type_id;
  60. // setBodyPartsByPatientType(patientTypeId);
  61. }
  62. // Dispatch the action using useDispatch in a component
  63. },
  64. },
  65. extraReducers: (builder) => {
  66. builder
  67. .addCase(getPatientTypes.pending, (state) => {
  68. state.loading = true;
  69. state.error = null;
  70. })
  71. .addCase(getPatientTypes.fulfilled, (state, action) => {
  72. state.loading = false;
  73. state.items = action.payload;
  74. })
  75. .addCase(getPatientTypes.rejected, (state, action) => {
  76. state.loading = false;
  77. state.error = action.payload as string;
  78. });
  79. },
  80. });
  81. export default patientTypeSlice.reducer;