Cannot Read properties of undefined when mapping data from graphql using react typescript

Issue

I have dogs component like this

const Dogs: React.FC = () => {
  const { loading, error, data } = useQuery(GET_DOGS);
  console.log(data)
  const renderedOption = data ? data.dogs.map(({dog, index}: {dog:any, index:number}) => (
    <option key={dog.id} value={dog.breed}>
      {dog.breed}
    </option>
  )) : "" ;

  return (
    <>
      {loading && "Loading..."}
      {error && `Error: ${error.message}`}
      {renderedOption}
    </>
  );
};

and ihave query for graphql like this

export const GET_DOGS = gql`
  {
    dogs {
      id
      breed
    }
  }
`;

and why its error: TypeError: Cannot read properties of undefined (reading ‘breed’) when i console.log(data) its appear and query its successfully, i also check my network to on browser its 200 status code. But i dont know when im try to mapp that data its error like that.

Solution

try to change your renderOption to this and let me know if it will work.

const renderedOption = data ? data.dogs.map((dog:any, index: number) => (
    <option key={dog?.id} value={dog?.breed}>
      {dog?.breed}
    </option>
  )) : "" ; 

Answered By – crispengari

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published