0

Looking for the shortest, most elegant wat to write this. I really like option 2. However, i get this error:

Argument of type 'boolean[]' is not assignable to parameter of type 'SetStateAction<ISlugSegment[]>

Which makes sense cause in #2 I am returning endpoint.autoGenerate, which is a boolean.

So, asking for some guidance here on how to re-rewrite #1 in the shortest way.

This is React by the way. Using the useState hook.

let [_endpoints, _setEndpoints] = useState(params.endpoints);

// 1. verbose (imperative?)
    const copiedEndpoints = _endpoints.map((endpoint: ISlugSegment) => {
      endpoint.autoGenerate = (endpoint.localeKey === _selectedLocale) ? endpoint.autoGenerate = false : endpoint.autoGenerate;
      return endpoint;
    });
_setEndpoints(copiedEndpoints);
// end

// 2. short: 1 line (functional?)
    _setEndpoints(_endpoints.map((endpoint: ISlugSegment) => (endpoint.localeKey === _selectedLocale) ? endpoint.autoGenerate = false : endpoint.autoGenerate));
// end

#2 results in an array of Booleans instead of an Array with ISlugSegments Objects. And what I need is the latter.

San Jay Falcon
  • 993
  • 1
  • 9
  • 20
  • Do you even have to `_setEndpoints` when you mutate some `endpoint`s, but keep the same objects? – Manfred Apr 09 '22 at 14:27
  • Yes, endpoints is existent: an Array filled with Objects of type ISlugSegments. – San Jay Falcon Apr 09 '22 at 15:05
  • No doubt, but you initialize your `_endpoints`state already with `useState` to the array `params.endpoints`. In fact, as updating state triggers a re-rendering, doing so in _every_ render cycle should create an infinite loop, no? – Manfred Apr 10 '22 at 08:48

1 Answers1

0

You can use the second approach if you satisfy Typescript by explicitly stating the types to useState

let [_endpoints, _setEndpoints] = useState<Array<ISlugSegment|boolean>>(params.endpoints)
D.B.K
  • 410
  • 2
  • 15