简体   繁体   中英

Uncaught error: TypeError: data.map is not a function

Could you please help me here? I want to map through a response object (example below). I don't have any errors in VSC but in browser there is an error: Uncaught error: TypeError: data.map is not a function

{
  "title":"some title",
  "info":"some info",
  "users":
  [
    {
      "id":1,
      "name":"name1",
      "surname":"surname1",
      "email":"email1",
    },
    {
      "id":2,
      "name":"name2",
      "surname":"surname2",
      "email":"email2",
    },
 ....
  ],
"resource":
{
  "url":"some url",
  "description":"some description"
  }
}

here is my interfaces:

export interface IUsers {
  id: number,
  name: string,
  surname: string,
  email: string
}

export interface IData {
  title: string,
  info: string,
  users: IUsers,
  resource: {
    url: string,
    description: string
  }
}

What i've got for now:

const { data } = DataAPI.useFetchAllDataQuery('')
...
{data  && data.map(item => item.users.map(user => (
 <User user={user} key={user.id}/>)))}

should i try data.users.map(...) --> property 'users' doesn't exist on type IData[].

May be it's because of the fact that 'data' is not an array, but i'm not sure how to use this construction Object.entries(data).map()...

Can you try doing something like this?

const { data } = await DataAPI.useFetchAllDataQuery('') // Assuming this is a promise
{data && data.users.map(user => (<User user={user} key={user.id}>))}

or maybe optional chaining

{data?.users?.map(user => (<User user={user} key={user.id}>))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM