27 Feb 2023
	
		
		06:11 PM
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 - last edited on 
    
	
		
		
		20 Apr 2023
	
		
		08:49 AM
	
	
	
	
	
	
	
	
	
	
	
	
	
	
 by 
				
		 educampver
		
			educampver
		
		
		
		
		
		
		
		
	
			
		
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))
      })
  }, []);
					
				
			
			
				
			
			
				Solved! Go to Solution.
27 Feb 2023 06:37 PM - edited 27 Feb 2023 06:39 PM
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.
27 Feb 2023 07:19 PM
I recommended the following changes:
Original code:
const entities = response?.entities;Proposed change:
const entities = response?.entities || [];
