fix: properly convert tag objects to strings before API update
- Extract tag names from object/string format before sending to API - API expects array of strings, not objects - Reload recipe after tag changes to get proper structure from API - Fixes 'Failed to add tag' error on recipe detail page
This commit is contained in:
@@ -126,8 +126,13 @@ function RecipeDetail() {
|
||||
|
||||
const trimmedTag = tagInput.trim();
|
||||
|
||||
// Convert existing tags to string array (handle both string and object formats)
|
||||
const existingTagNames = (recipe.tags || []).map(tagItem =>
|
||||
typeof tagItem === 'string' ? tagItem : tagItem.tag?.name || tagItem.name
|
||||
);
|
||||
|
||||
// Check if tag already exists on recipe
|
||||
if (recipe.tags?.includes(trimmedTag)) {
|
||||
if (existingTagNames.includes(trimmedTag)) {
|
||||
setTagInput('');
|
||||
// Keep focus in input field
|
||||
setTimeout(() => tagInputRef.current?.focus(), 0);
|
||||
@@ -136,11 +141,12 @@ function RecipeDetail() {
|
||||
|
||||
try {
|
||||
setSavingTags(true);
|
||||
const updatedTags = [...(recipe.tags || []), trimmedTag];
|
||||
// Send array of tag names (strings) to API
|
||||
const updatedTags = [...existingTagNames, trimmedTag];
|
||||
await recipesApi.update(id, { tags: updatedTags });
|
||||
|
||||
// Update local state
|
||||
setRecipe({ ...recipe, tags: updatedTags });
|
||||
// Reload the recipe to get the updated tag structure from API
|
||||
await loadRecipe(id);
|
||||
setTagInput('');
|
||||
|
||||
// Reload available tags to include newly created ones
|
||||
@@ -161,11 +167,15 @@ function RecipeDetail() {
|
||||
|
||||
try {
|
||||
setSavingTags(true);
|
||||
const updatedTags = recipe.tags?.filter(tag => tag !== tagToRemove) || [];
|
||||
// Convert existing tags to string array and filter out the removed tag
|
||||
const existingTagNames = (recipe.tags || []).map(tagItem =>
|
||||
typeof tagItem === 'string' ? tagItem : tagItem.tag?.name || tagItem.name
|
||||
);
|
||||
const updatedTags = existingTagNames.filter(tag => tag !== tagToRemove);
|
||||
await recipesApi.update(id, { tags: updatedTags });
|
||||
|
||||
// Update local state
|
||||
setRecipe({ ...recipe, tags: updatedTags });
|
||||
// Reload the recipe to get the updated tag structure from API
|
||||
await loadRecipe(id);
|
||||
} catch (err) {
|
||||
console.error('Failed to remove tag:', err);
|
||||
alert('Failed to remove tag');
|
||||
|
||||
Reference in New Issue
Block a user