This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
react-rest-request/src/reducer.ts
Dmitriy Pleshevskiy 243f4f77e5 feat!(client): add client fetch based
breaking!(context): client prop instead base url
refac: change axios response to client response
chore(deps): remove axios
chore: update example

Closes #2
2020-11-05 00:23:57 +03:00

45 lines
1.3 KiB
TypeScript

import { ClientResponse } from './client';
export type RequestState<R> = Readonly<{
data: R | null;
loading: boolean;
isCalled: boolean;
prevHeaders?: Record<string, string>;
prevVariables?: Record<string, any>;
prevParams?: Record<string, any>
}>
export type RequestAction<R> =
| { type: 'call', headers: Record<string, string>, variables: Record<string, any>, params?: Record<string, any> }
| { type: 'success', response: ClientResponse<R> }
| { type: 'failure', response: ClientResponse<R> }
export function requestReducer<R>(state: RequestState<R>, action: RequestAction<R>) {
switch (action.type) {
case 'call': {
return {
...state,
loading: true,
isCalled: true,
prevHeaders: action.headers,
prevVariables: action.variables,
prevParams: action.params,
};
}
case 'success': {
return {
...state,
loading: false,
data: action.response.data,
};
}
case 'failure': {
return {
...state,
loading: false,
data: null,
// TODO: need to append errors
};
}
}
}