0

I have the following React code,

const useDynamicReplaceVariable = ({ label, formikValues, fieldsTypes }) => {
  const { locale } = useTranslationState();

  const formattedLabel = useMemo(() => {
    const variablesRegex = /\?([\w-]+)\?/g;
    let labelResult = label;
    
    if (variablesRegex.test(label)) {
      labelResult = ' ';
      if (Object.keys(formikValues).length > 0) {
        labelResult = label.replace(variablesRegex, (_, ...[variable]) => {
          const type = fieldsTypes[variable];
          // Set undefined or null to empty
          let variableValue = (formikValues[variable] === undefined || formikValues[variable] == null) ? '' : formikValues[variable];
          if (variableValue && [DesignerDdTypes.DatePicker, DesignerDdTypes.DatetimePicker].includes(type)) {
            variableValue = dateToString(variableValue, locale, type === DesignerDdTypes.DatetimePicker);
          }
          return variableValue;
        });
      }
    }
    return labelResult;
    // eslint-disable-next-line react-hooks/exhaustive-deps  
  }, [label, JSON.stringify(formikValues)]);

  return { formattedLabel };
};

I can't understand the line labelResult = label.replace(variablesRegex, (_, ...[variable]), when no variable is defined, how come spread syntax is applied over it?

2
  • it's destructuring the rest parameters to access the first element (of course in this case it is the same as not using rest parameters at all... so it could just be (_, variable)) Commented Jan 11, 2023 at 21:59
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 11, 2023 at 21:59

1 Answer 1

2

...[variable] is a shorthand for

function someFunction(...args) {
  const [variable] = args
}

someFunction(1, 2, 3, 4, 5)

function someFunction(arg1, ...args) {
  console.log('arg1', arg1)
  console.log('args', args)
  const [variable] = args
  console.log('variable', variable)
}

someFunction(1, 2, 3, 4, 5)

function someFunction(arg1, ...[variable]) {
  console.log('arg1', arg1)
  console.log('variable', variable)
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.