diff --git a/src/components/AuthorsSelect.tsx b/src/components/AuthorsSelect.tsx index 071d600f..4144aef4 100644 --- a/src/components/AuthorsSelect.tsx +++ b/src/components/AuthorsSelect.tsx @@ -1,5 +1,5 @@ import { get, isEqual } from 'lodash'; -import React, { ReactElement, useState } from 'react'; +import React, { ReactElement, useEffect, useRef, useState } from 'react'; import { Styles } from 'react-select'; import type { WP_REST_API_Error, @@ -53,30 +53,61 @@ const AuthorsSelect = ( props: AuthorsSelectProps ): ReactElement => { const isDisabled = ! hasAssignAuthorAction; const [ selected, setSelected ] = useState( [] ); - - const preloadedAuthorIDs = preloadedAuthorOptions.authors.map( author => author.value ); - - if ( ! selected.length && isEqual( preloadedAuthorIDs, currentAuthorIDs ) ) { - setSelected( preloadedAuthorOptions.authors ); - } else if ( currentAuthorIDs !== undefined && currentAuthorIDs.length && ! selected.length ) { - - const path = addQueryArgs( - '/authorship/v1/users/', - { - include: currentAuthorIDs, - orderby: 'include', - post_type: postType, - } - ); - - const api: Promise = apiFetch( { path } ); - - api.then( users => { - setSelected( users.map( createOption ) ); - } ).catch( ( error: WP_REST_API_Error ) => { - onError( error.message ); - } ); - } + const hasInitializedSelection = useRef( false ); + + useEffect( () => { + const preloadedAuthorIDs = preloadedAuthorOptions.authors.map( author => author.value ); + + if ( hasInitializedSelection.current || selected.length ) { + return; + } + + if ( isEqual( preloadedAuthorIDs, currentAuthorIDs ) ) { + setSelected( preloadedAuthorOptions.authors ); + hasInitializedSelection.current = true; + return; + } + + if ( currentAuthorIDs !== undefined && currentAuthorIDs.length ) { + hasInitializedSelection.current = true; + + const path = addQueryArgs( + '/authorship/v1/users/', + { + include: currentAuthorIDs, + orderby: 'include', + post_type: postType, + } + ); + + let isCancelled = false; + const api: Promise = apiFetch( { path } ); + + api.then( users => { + if ( isCancelled ) { + return; + } + + setSelected( users.map( createOption ) ); + } ).catch( ( error: WP_REST_API_Error ) => { + if ( isCancelled ) { + return; + } + + onError( error.message ); + } ); + + return () => { + isCancelled = true; + }; + } + }, [ + currentAuthorIDs, + onError, + postType, + preloadedAuthorOptions.authors, + selected.length, + ] ); /** * Asynchronously loads the options for the control based on the search parameter.