Skip to content

Commit

Permalink
FlatTermSelector: Invalidate optimistic update if term creation fails (
Browse files Browse the repository at this point in the history
…#59945)


Unlinked contributors: TMFHokies.

Co-authored-by: Mamaduka <mamaduka@git.wordpress.org>
Co-authored-by: fabiankaegy <fabiankaegy@git.wordpress.org>
  • Loading branch information
3 people committed Mar 18, 2024
1 parent f6b40cb commit 6803841
Showing 1 changed file with 13 additions and 8 deletions.
Expand Up @@ -40,10 +40,13 @@ const isSameTermName = ( termA, termB ) =>
unescapeString( termB ).toLowerCase();

const termNamesToIds = ( names, terms ) => {
return names.map(
( termName ) =>
terms.find( ( term ) => isSameTermName( term.name, termName ) ).id
);
return names
.map(
( termName ) =>
terms.find( ( term ) => isSameTermName( term.name, termName ) )
?.id
)
.filter( ( id ) => id !== undefined );
};

export function FlatTermSelector( { slug } ) {
Expand Down Expand Up @@ -193,9 +196,8 @@ export function FlatTermSelector( { slug } ) {
setValues( uniqueTerms );

if ( newTermNames.length === 0 ) {
return onUpdateTerms(
termNamesToIds( uniqueTerms, availableTerms )
);
onUpdateTerms( termNamesToIds( uniqueTerms, availableTerms ) );
return;
}

if ( ! hasCreateAction ) {
Expand All @@ -209,14 +211,17 @@ export function FlatTermSelector( { slug } ) {
)
.then( ( newTerms ) => {
const newAvailableTerms = availableTerms.concat( newTerms );
return onUpdateTerms(
onUpdateTerms(
termNamesToIds( uniqueTerms, newAvailableTerms )
);
} )
.catch( ( error ) => {
createErrorNotice( error.message, {
type: 'snackbar',
} );
// In case of a failure, try assigning available terms.
// This will invalidate the optimistic update.
onUpdateTerms( termNamesToIds( uniqueTerms, availableTerms ) );
} );
}

Expand Down

0 comments on commit 6803841

Please sign in to comment.