Skip to content

Commit

Permalink
useAsyncList: flush state updates when processing queue (#48238)
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr authored and fullofcaffeine committed Feb 28, 2023
1 parent 9d28256 commit 427d212
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 12 deletions.
23 changes: 11 additions & 12 deletions packages/compose/src/hooks/use-async-list/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* WordPress dependencies
*/
import { useEffect, useState } from '@wordpress/element';
import { flushSync, useEffect, useState } from '@wordpress/element';
import { createQueue } from '@wordpress/priority-queue';

type AsyncListConfig = {
Expand Down Expand Up @@ -57,17 +57,16 @@ function useAsyncList< T >(
setCurrent( firstItems );

const asyncQueue = createQueue();
const append = ( nextIndex: number ) => () => {
if ( list.length <= nextIndex ) {
return;
}
setCurrent( ( state ) => [
...state,
...list.slice( nextIndex, nextIndex + step ),
] );
asyncQueue.add( {}, append( nextIndex + step ) );
};
asyncQueue.add( {}, append( firstItems.length ) );
for ( let i = firstItems.length; i < list.length; i += step ) {
asyncQueue.add( {}, () => {
flushSync( () => {
setCurrent( ( state ) => [
...state,
...list.slice( i, i + step ),
] );
} );
} );
}

return () => asyncQueue.reset();
}, [ list ] );
Expand Down
4 changes: 4 additions & 0 deletions packages/element/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### New Features

- Started exporting the `flushSync` function from `react-dom`

## 5.4.0 (2023-02-15)

## 5.3.0 (2023-02-01)
Expand Down
8 changes: 8 additions & 0 deletions packages/element/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,14 @@ _Parameters_

- _component_ `import('./react').WPComponent`: Component's instance.

### flushSync

Forces React to flush any updates inside the provided callback synchronously.

_Parameters_

- _callback_ `Function`: Callback to run synchronously.

### forwardRef

Component enhancer used to enable passing a ref to its wrapped component.
Expand Down
8 changes: 8 additions & 0 deletions packages/element/src/react-platform.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import {
createPortal,
findDOMNode,
flushSync,
render,
hydrate,
unmountComponentAtNode,
Expand All @@ -28,6 +29,13 @@ export { createPortal };
*/
export { findDOMNode };

/**
* Forces React to flush any updates inside the provided callback synchronously.
*
* @param {Function} callback Callback to run synchronously.
*/
export { flushSync };

/**
* Renders a given element into the target DOM node.
*
Expand Down

0 comments on commit 427d212

Please sign in to comment.