Skip to content

Commit

Permalink
feat(settings): add settings to use payload as error instead
Browse files Browse the repository at this point in the history
  • Loading branch information
Pixeladed committed Oct 20, 2020
1 parent fad78ff commit 2dbb3e2
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 7 deletions.
15 changes: 10 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import * as selectors from './selectors';
import * as reducers from './reducers';
import { getInitialState } from './state';
import { AsyncAdapterOptions } from './types';
import { setSettings } from './settings';

const createAsyncAdapter = () => ({
...reducers,
getSelectors: () => selectors,
getInitialState,
});
const createAsyncAdapter = (options: Partial<AsyncAdapterOptions>) => {
setSettings(options);
return {
...reducers,
getSelectors: () => selectors,
getInitialState,
};
};

export * from './types';
export default createAsyncAdapter;
6 changes: 5 additions & 1 deletion src/reducers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { AsyncThunk } from '@reduxjs/toolkit';
import { AsyncState, AsyncStatus } from './types';
import { getDefaultStatus } from './utils';
import { getSettings } from './settings';

/**
* Handle async status updates for an async thunk pending action
Expand Down Expand Up @@ -53,9 +54,12 @@ export const handleRejected = <Data, Returned, ThunkArg, ThunkApiConfig>(
const { typePrefix } = asyncThunk;
const currentStatus =
state.status[typePrefix] || getDefaultStatus(typePrefix);
const settings = getSettings();
const error = settings.usePayloadAsError ? action.payload : action.error;

const newStatus: AsyncStatus = {
...currentStatus,
error: action.error,
error,
loaded: false,
loading: false,
};
Expand Down
14 changes: 14 additions & 0 deletions src/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { AsyncAdapterOptions } from './types';

const settings: AsyncAdapterOptions = {
usePayloadAsError: false,
};

export const getSettings = () => Object.freeze(settings);

export const setSettings = (newSettings: Partial<AsyncAdapterOptions>) => {
for (const property in newSettings) {
const key = property as keyof AsyncAdapterOptions;
settings[key] = newSettings[key];
}
};
6 changes: 5 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { SerializedError } from '@reduxjs/toolkit';

export interface AsyncAdapterOptions {
usePayloadAsError: boolean;
}

export interface AsyncState<T> {
status: { [name: string]: AsyncStatus | undefined };
data: T;
Expand All @@ -9,6 +13,6 @@ export interface AsyncStatus {
name: string;
loading: boolean;
loaded: boolean;
error: SerializedError | undefined;
error: SerializedError | any | undefined;
lastLoaded: string | undefined;
}

0 comments on commit 2dbb3e2

Please sign in to comment.