How to put optional parameter in Reactjs

Asked

Viewed 54 times

-1

I need to send a request, but there is a parameter that is optional, and I must only send it on one condition. It’s like this:

const [blocoSelect, setBlocoSelect] = useState("nenhum");
        params: {
          initial_date: dateRange.startDate._d,
          final_date: dateRange.endDate._d,
          order: isMaisAntigasSelected ? 'DESC' : 'ASC',
          condo_id: condoSelect,
          blocs: isManuBlocs,
          areas: isManuArea,
          // bloc_name: opcional
        }

That one bloc_name is optional, it will only get mine blocoSelect unlike any other, I tried something like:

        params: {
          initial_date: dateRange.startDate._d,
          final_date: dateRange.endDate._d,
          order: isMaisAntigasSelected ? 'DESC' : 'ASC',
          condo_id: condoSelect,
          blocs: isManuBlocs,
          areas: isManuArea,
          {
            blocoSelect!=="nenhum" &&
           bloc_name: opcional  }
        }

But I saw that the syntax was wrong and I don’t know how to fix it

1 answer

1

Even if you set your example (following your line of reasoning), the result would never be undefined - would return false as value, that is, the field would always be sent. See below:

const addParam = false;
const params = {
  key: addParam && 'valor',
  key2: !addParam && 'valor',
};

console.log(params);

To place an optional attribute on an object, you can make use of a ternary operator as you did on order:

const addParam = false;
const params = {
  key: addParam ? 'valor' : undefined,
  key2: !addParam ? 'valor' : undefined,
};

console.log(params);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.