2

First all my question is not rehash of ES6 double destructure

Look at the following code - Apollo Client GraphQL

import { gql, useQuery, useMutation } from '@apollo/client';
...
const { loading, error, data } = useQuery(TREATMENTS);

It would be nicer to write it this way:

   const { loading, error, data : {treatments} } = useQuery(TREATMENTS);

However, unfortunately I've got the following error:

TypeError: Cannot read property 'treatments' of undefined
TreadDetails
C:/Users/albertly/Downloads/git/individual-claims/src/TreatDetails.tsx:35

  32 | `;
  33 | 
  34 | function TreadDetails(): React.ReactElement {
> 35 |   const { loading, error, data : {treatments} } = useQuery(TREATMENTS);
  36 |  // const [treatments, setTreatments] = useState<Treatment[]>([]);
  37 |   const { state: stateApp, dispatch: dispatchApp } = useContext(AppContext); 

I understand perfectly well why it is happening.

My question is: Is there some syntactical trick to make it work ?

Edited: It has been brought to my attention that there is a quite similar question Destructuring with nested objects and default values

Albert Lyubarsky
  • 438
  • 1
  • 7
  • 15
  • The question https://stackoverflow.com/questions/39049399/destructuring-with-nested-objects-and-default-values - "Destructuring with nested objects and default values" does answer my question. Although my question is more specific I would figure out what to do if I found this answer and I wouldn't ask it. When I tried to delete this question I've got a system suggestion that deleting is not recommended. What to do? – Albert Lyubarsky Oct 29 '20 at 09:17
  • 1
    May be it's better to leave it as is (without status duplicate) because it may be helpful to community - the problem is more clear in my question. – Albert Lyubarsky Oct 29 '20 at 09:24

1 Answers1

5

Provide an initial value for data to destructure from.

const { loading, error, data: { treatments } = {} } = useQuery(TREATMENTS);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181