Home > Blockchain >  Getting a Type error when loading data from API in react using typescript
Getting a Type error when loading data from API in react using typescript

Time:01-09

I am getting the following error:

ERROR in src/Components/Pages/Languages/LanguagesPage.tsx:41:29 TS2339: Property 'languageId' does not exist on type '[]'. 39 |

    40 | {data.languages.map((language: []) => ( 41 | | ^^^^^^^^^^ 42 | {language.languageId} - {language.name} 43 | 44 | ))}

    ERROR in src/Components/Pages/Languages/LanguagesPage.tsx:42:23 T. S2339: Property 'languageId' does not exist on type '[]'. 40 | {data.languages.map((language: []) => ( 41 | 42 | {language.languageId} - {language.name} | ^^^^^^^^^^ 43 | 44 | ))} 45 |

ERROR in src/Components/Pages/Languages/LanguagesPage.tsx:42:47 TS2339: Property 'name' does not exist on type '[]'. 40 | {data.languages.map((language: []) => ( 41 | 42 | {language.languageId} - {language.name} | ^^^^ 43 | 44 | ))} 45 |

I can see my data in the log. I just can not finger out how to get it.

enter image description here

Here is my code.

import React from 'react';  import { gql, useQuery } from '@apollo/client';

 const GET_LANGUAGES_QUERY = gql` query Query { languages { languageId name
    }   }  `;

 export const LanguagesPage: React.FC = () => { const { loading, error, data } = useQuery(GET_LANGUAGES_QUERY);

if (error) return <p>Error Getting Data</p>; if (loading) return <p>Loading</p>; console.log(data);

return (
    <main>
      <div>current Language: Tabla</div>
      <h3>Which Language do you want to Learn?</h3>
        {data.languages.map((language: []) => (
          <li key={language.languageId}>
            {language.languageId} - {language.name}
          </li>
        ))}
      </ul>
      </main>
     );    

CodePudding user response:

 data.languages.map((language: [])

Here you are saying that every item of languages is an array but it's an object instead

CodePudding user response:

Is language actually an array? Try console logging the typeof and contents of the languages variable.

If it is an array, you cannot use the dot syntax to access contents. You will need to rethink the way you extract languageId and name.

If it is an object, stop using the [] in language: [], change it to {} and the rest of it should work just fine.

  • Related