Skip to content

Commit

Permalink
Enhancement : Carbonise Appointment widget Code Review
Browse files Browse the repository at this point in the history
  • Loading branch information
donaldkibet committed Sep 14, 2021
1 parent ea32b11 commit 8f76b15
Showing 1 changed file with 56 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,25 +1,73 @@
import { useEffect, useState, useMemo } from 'react';
import { useEffect, useMemo, useReducer } from 'react';
import dayjs from 'dayjs';
import { getAppointments } from '../appointments/appointments.resource';
import { Appointment } from '../types';

enum ActionTypes {
pending = 'pending',
resolved = 'resolved',
error = 'error',
}
interface Pending {
type: ActionTypes.pending;
}

interface Error {
type: ActionTypes.error;
payload: Error;
}

interface Resolved {
type: ActionTypes.resolved;
payload: Array<Appointment>;
}

type Action = Pending | Error | Resolved;

interface PatientAppointments {
status: 'pending' | 'resolved' | 'error';
patientAppointments: Array<Appointment>;
error?: null | Error;
}

function reducer(state: PatientAppointments, action: Action): PatientAppointments {
switch (action.type) {
case ActionTypes.pending:
return {
status: 'pending',
...state,
};
case ActionTypes.resolved:
return {
status: 'resolved',
patientAppointments: action.payload,
error: null,
};
case ActionTypes.error:
return {
status: 'error',
patientAppointments: null,
error: action.payload,
};
default:
return state;
}
}

export const useAppointments = (patientUuid: string) => {
const [patientAppointments, setPatientAppointments] = useState<Array<Appointment>>([]);
const [error, setError] = useState<Error>(null);
const [status, setStatus] = useState<'pending' | 'resolved' | 'error'>('pending');
const initialState: PatientAppointments = { status: 'pending', patientAppointments: [] };
const [{ status, patientAppointments, error }, dispatch] = useReducer(reducer, initialState);

useEffect(() => {
if (patientUuid) {
const ac = new AbortController();
const startDate = dayjs(new Date().toISOString()).subtract(6, 'month').toISOString();
getAppointments(patientUuid, startDate, ac).then(
({ data }) => {
setPatientAppointments(data);
setStatus('resolved');
dispatch({ type: ActionTypes.resolved, payload: data });
},
(error) => {
setError(error);
setStatus('error');
dispatch({ type: ActionTypes.error, payload: error });
},
);
return () => ac.abort();
Expand Down

0 comments on commit 8f76b15

Please sign in to comment.