cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Getting - entities is possibly 'undefined' error

SantiPalacios
Dynatrace Advisor
Dynatrace Advisor

I am trying to work on a fairly basic app that calls Dynatrace API for entities and then want to parse out the entityId and build an array of entities. I think that this might be specific to Typescript and not sure how to solve it. I know that I am getting an result array of objects, but when trying to use map, is telling me that entities is possibly undefined. Any help would be appreciated.

 

const [entitiesArray, setEntitiesArray] = useState<any[]>([]);
  useEffect(() => {
    monitoredEntitiesClient.getEntities(
      {
        entitySelector: 'type("HOST"),tag("OpenShift_App_Nodes")',
        from: 'now-1y/M',
        pageSize: 900
      })
      .then(response => {
        // console.log('response:', response)
        const entities = response?.entities
        console.log('entities:', entities)
        setEntitiesArray(entities.map(entity => entity?.entityId))
      })
  }, []);
2 REPLIES 2

SantiPalacios
Dynatrace Advisor
Dynatrace Advisor

From @Michael_Beemer :

Basically, you're using optional chaining which returns either the value or undefined. In the solution I proposed ( const entities = response?.entities || []; ), it uses OR logic because if the entities property is missing, undefined is evaluations to a falsy value. That will set entities to an empty array. The ??  is called nullish coalescing ( entities?.map(…) ?? [] ) and is useful when the first value should be used if it's any other than undefined, even if it's a falsy value such as 0 or false.

Hope that's useful and makes sense.

I recommended the following changes:

Original code:

const entities = response?.entities;

Proposed change:

const entities = response?.entities || [];

 

Featured Posts