Currently, I am attempting to utilize the eval()
function to dynamically update a variable that must be accessed by path in the format myArray[0][0[1][0]...
. Strangely enough, when I try this approach, I encounter the following error:
Uncaught TypeError: Cannot set properties of undefined (setting '$folded')
Interestingly, if I avoid using eval and opt for something like
productCategoriesTree[1].$folded = false
- it works without any issues.
My environment involves Vue 3, so there is a possibility that this error might be related to Vue in some way.
The culprit seems to be the addNewProductCategory()
function:
// useProductCategoriesTree.ts
import { v4 as uuidv4 } from 'uuid'
import TreeItem from '@/types/TreeItem'
import { try as tryCatch } from 'radash'
import { getCurrentInstance } from 'vue'
import { ProductCategory, ProductCategoryTreeInput } from '@/types/graphql/graphql'
import productCategoryApi, { FRAGMENT_PRODUCT_CATEGORY_TREE } from '@/api/productCategoryApi'
export function useProductCategoriesTree() {
let productCategoriesTree = $ref<TreeItem<ProductCategory>[]>([])
const { emit } = getCurrentInstance() as any
const getProductCategoriesTree = async () => {
const [error, productCategories] = await tryCatch(productCategoryApi.getProductCategoryList)(FRAGMENT_PRODUCT_CATEGORY_TREE)
productCategoriesTree = buildProductCategoriesTree(productCategories)
}
const buildProductCategoriesTree = (productCategories: ProductCategory[]): TreeItem<ProductCategory>[] => {
return productCategories.map(productCategory => ({
data: productCategory,
children: (productCategory.children && productCategory.children.length)
? buildProductCategoriesTree(productCategory.children)
: undefined
}))
}
const selectProductCategory = (productCategoryUuid: string) => {
emit('select', productCategoryUuid)
}
// treePath could be [0, 1, 0, 0, 1] - it is dynamic
const addNewProductCategory = (parentCategoryUuid: string, treePath: number[]) => {
const newProductCategory = {
uuid: `__NEW-${uuidv4()}`,
namePlural: 'new',
parent: { uuid: parentCategoryUuid }
}
if (!productCategoriesTree[1].children) {
productCategoriesTree[1].children = []
}
productCategoriesTree[1].children?.push({
data: newProductCategory as ProductCategory,
children: [],
})
console.log(`productCategoriesTree[${treePath.join('][')}].$folded = false`)
// productCategoriesTree[1].$folded = false
// this works
productCategoriesTree[1].$folded = false
// this does not work
eval(`productCategoriesTree[${treePath.join('][')}].$folded = false`)
}
getProductCategoriesTree()
return $$({
productCategoriesTree,
selectProductCategory,
addNewProductCategory,
})
}