Skip to content

Commit

Permalink
Add more options
Browse files Browse the repository at this point in the history
  • Loading branch information
manzoorwanijk committed Oct 25, 2024
1 parent 40b50c8 commit 7fd385f
Showing 1 changed file with 40 additions and 3 deletions.
43 changes: 40 additions & 3 deletions projects/js-packages/wp-data-sync/src/create-wp-data-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,16 +143,19 @@ export type WpDataSyncOptions< Shape extends object > = {
* The endpoint to sync the data with.
*/
endpoint: string;

/**
* The initial state of the data
*/
initialState?: Shape;

/**
* A function to extract the data from the fetch response.
*
* If not provided, the response will be used as is.
*/
extractFetchResponse?: ( response: unknown ) => Partial< Shape >;

/**
* A function to prepare the request for updating the data.
*
Expand All @@ -167,6 +170,29 @@ export type WpDataSyncOptions< Shape extends object > = {
* or if you use a reducer key different from the name.
*/
getSliceFromState?: ( state: object ) => WpDataSyncState< Shape >;

/**
* Whether to fetch the data on initialization.
*
* You may disable it if you set the initial state.
*
* @default true
*/
fetchOnInit?: boolean;

/**
* Whether to fetch the data on update.
*
* @default false
*/
fetchAfterUpdate?: boolean;

/**
* Whether to do optimistic updates.
*
* @default true
*/
doOptimisticUpdates?: boolean;
};

/**
Expand All @@ -180,8 +206,11 @@ export type WpDataSyncOptions< Shape extends object > = {
export function createWpDataSync< Shape extends object, Name extends string >(
name: Name,
{
doOptimisticUpdates = true,
endpoint,
extractFetchResponse,
fetchAfterUpdate = false,
fetchOnInit = true,
getSliceFromState = defaultGetSliceFromState( name ),
initialState,
prepareUpdateRequest,
Expand All @@ -193,7 +222,9 @@ export function createWpDataSync< Shape extends object, Name extends string >(
resolvers: {
[ `get${ capitalizedName }` as const ]: () => {
return async function ( { dispatch } ) {
await dispatch[ `fetch${ capitalizedName }` ]();
if ( fetchOnInit ) {
await dispatch[ `fetch${ capitalizedName }` ]();
}
};
},
},
Expand Down Expand Up @@ -266,15 +297,21 @@ export function createWpDataSync< Shape extends object, Name extends string >(
const setStatus = dispatch[ `setStatusFor${ capitalizedName }` ];

try {
// Optimistically update the data.
dispatch[ `set${ capitalizedName }` ]( payload );
if ( doOptimisticUpdates ) {
// Optimistically update the data.
dispatch[ `set${ capitalizedName }` ]( payload );
}

setStatus( 'updating' );

const data = prepareUpdateRequest?.( payload ) ?? payload;

await apiFetch( { method: 'POST', path: endpoint, data } );

if ( fetchAfterUpdate ) {
await dispatch[ `fetch${ capitalizedName }` ]();
}

setStatus( 'idle' );
} catch ( error ) {
// Revert the value to its previous state.
Expand Down

0 comments on commit 7fd385f

Please sign in to comment.