-1

By dynamically I mean that this prop won't be the same depending where I am checking it from. For example, I have this hook:

export const useErrorBorder = (fieldName: string) => {
  const { formState: { errors } } = useFormContext()
  const colors = { clean: 'blue.500', error: 'red.500' }

  let showErrorBorder = colors.clean

  if (errors && Object.keys(errors)?.length && fieldName) {
    showErrorBorder = colors.error
  } else {
    showErrorBorder = colors.clean
  }

  if (!fieldName) {
    showErrorBorder = 'inherit'
  }

  return showErrorBorder
}

Where I need to check if fieldName exists in the errors object of the formState from useFormContext hook.

So when I call this hook, I use like this:

  const handleErrorHook = useErrorBorder(
    Object.keys(errors)?.length ? errors?.logic[conditionIndex]?.skipQuestionsSelect : '',
  )

Or depending if I call it on another component:

  const handleErrorHook = useErrorBorder(
    Object.keys(errors)?.length ? errors?.logic[conditionIndex]?.scenarios[scenarioIndex]?.operator : ''
  )
<Comp focusBorderColor={handleErrorHook?.showErrorBorder || 'inherit'}` />

As you noticed skipQuestionsSelect is not inside the scenarios array. And, when skipQuestionsSelect or operator are empty they will be remove from their positions

So I am getting errors like these: enter image description here

So what will be the best solution to avoid this error?

Reacting
  • 5,543
  • 7
  • 35
  • 86
  • Why don’t you use `Object.keys(obj).includes('key')`? – MrMythical Aug 02 '21 at 18:17
  • Your error is referencing code that you didn't (fully) include in your question? Also, even though a screenshot looks nice, (also) include your error in a code block. – Kelvin Schoofs Aug 02 '21 at 18:20
  • Does this answer your question? [How to check if object property exists with a variable holding the property name?](https://stackoverflow.com/questions/11040472/how-to-check-if-object-property-exists-with-a-variable-holding-the-property-name) – Heretic Monkey Aug 02 '21 at 18:22

2 Answers2

1

You're not properly optional chaining your errors?.logic[conditionIndex]?.scenarios[scenarioIndex]?.operator bit.

If you want to optional chain with a [key] access, use ?.[key], e.g. errors?.logic?.[conditionIndex]?.scenarios?.[scenarioIndex]?.operator.

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
1

In Javascript there are two ways to access object properties, that are dot notation: something.bar or with bracket notation: something['bar'] With the bracket notation you can access the object properties dynamically passing the string value of the key inside the bracket.

So in your case that you have the key stored on a variable so you simply put the variable with the key name inside the brackets like this:

var objectKey = 'someKey';
var objectWithSomeKey = {
  someKey: 'Hello'
};

console.log(objectWithSomeKey[objectKey]);