Home > Blockchain >  How to add, update or remove nested objects with useState
How to add, update or remove nested objects with useState

Time:07-21

I have a possible infinite category tree and I would like to add, update or remove categories at any level with setState in react. I know this is possible with recursion but I don't have enough experience to manage this problem on my own. Here is how the data could possible look like:

const categories = [
  {
    id: "1",
    name: "category1",
    subCategories: [
      {
        id: "sub1",
        name: "subcategory1",
        subCategories: [
          { id: "subsub1", name: "subsubcategory1", subCategories: [] },
          { id: "subsub2", name: "subsubcategory2", subCategories: [] }
        ]
      },
      { id: "sub2", name: "subcategory2", subCategories: [] }
    ]
  },
  {
    id: "2",
    name: "category2",
    subCategories: []
  }
]

CodePudding user response:

Considering that your top level categories object is an object and not an array, the add and remove function could be the following (same pattern for update)

function add (tree, newCategory, parentId) {
    if(tree.id === parentId) 
      return {
        ...tree,
        subCategories: tree.subCategories.concat(newCategory)
      }
    return {
        ...tree, 
        subCategories: tree.subCategories.map(c => add(c, newCategory, parentId))
    }
}



function remove (tree, idToRemove) {
        if(tree.subCategories.map(c => c.id).includes(idToRemove)) 
          return {
            ...tree,
            subCategories: tree.subCategories.filter(c => c.id !== idToRemove)
          }
        return {
            ...tree, 
            subCategories: tree.subCategories.map(c => remove(c, idToRemove))
        }
    }

CodePudding user response:

this is how the recursive function would look like. the arguments:

id: id to look for

categories: the categories array to loop

nestSubCategory: (boolean) if we want to add the subcategory object in the subCategories array or not

subCategory: the category object we want to insert

const addCategories = (id, categories, index = 0, nestSubCategory, subCategory)=> {
      const cat = categories.find(item=> item.id === id)
      if(cat){
        if(nestSubCategory){
           cat.subCategories.push(subCategory)
        }else{
           cat.push(subCategory)
        }
      }else{
        if(categories[0].subCategories.length){
         return addCategories(id, categories[0].subCategories, nestSubCategory, subCategory)
        }
        else{
          console.log('no index')
          return
        }
      }
    
}

run it:

addCategories("subsub2", categories, true, { id: "blabla1", name: "blablacategory1", subCategories: [] })
console.log(JSON.stringify(categories))

remember to update the object in the state replacing the entire categories array once the function is executed. be careful with recursion

  • Related