Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useAsyncList: flush state updates when processing queue #48238

Merged
merged 3 commits into from
Feb 20, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
useAsyncList: flush state updates when processing queue
  • Loading branch information
jsnajdr committed Feb 20, 2023
commit 7648347637a9a51783f0018cd36c685561bb5613
12 changes: 7 additions & 5 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 @@ -61,10 +61,12 @@ function useAsyncList< T >(
if ( list.length <= nextIndex ) {
return;
}
setCurrent( ( state ) => [
...state,
...list.slice( nextIndex, nextIndex + step ),
] );
flushSync( () => {
setCurrent( ( state ) => [
...state,
...list.slice( nextIndex, nextIndex + step ),
] );
} );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While this PR restores the previous behavior (prior to the upgrade). I think it's still not perfect. Personally, I think we should be calling asyncQueue.add( {}, append( nextIndex + step ) ); outside the callback. kind of like I did here

#48085 (comment)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally, I think we should be calling asyncQueue.add outside the callback.

Pushed a commit that implements that 👍 Behavior-wise it's exactly the same, it just add all the work to the queue upfront, instead of adding each new task just in time right before the next iteration of the for of waitingList loop inside priority-queue.

asyncQueue.add( {}, append( nextIndex + step ) );
};
asyncQueue.add( {}, append( firstItems.length ) );
Expand Down