More Efficient Way to Destructure with Conditional in ReactJs

Viewed 72

I have this code in which we retrieve the data or get the data using useQuery. However, it fails anytime I attempt to call it using this method.

const { data: {getSubCategories} } = useQuery(FETCH_SUBCATEGORIES_QUERY);

It appears to throw an error stating that 'getSubCategories' is undefined, so I tried this method:

const { getSubCategories: subCategories } = { ...subCategoryData };
const { getChildCategory } = { ...data };

It works, but I think there is a better approach or more efficient way to destructure something with conditional syntaxes so it can't return undefined I guess I seem to notice it will take a few seconds before it will return data.

Would you mind commenting down below if you don't understand what I am trying to say or need more clarifications. Thank you.

2 Answers

It appears to throw an error stating that 'getSubCategories' is undefined

No, it's throwing an error when data is undefined. You can circumvent that by using a default:

const { data: {getSubCategories} = {} } = useQuery(FETCH_SUBCATEGORIES_QUERY);

If I've understood correctly you can try this: (safely destruct from the object)

const { data: {getSubCategories} } = useQuery(FETCH_SUBCATEGORIES_QUERY) || {};

Related