Djony
Djony

Reputation: 181

Property 'map' does not exist on type 'never'

When making an axios get request inside a next.js getServerSideProps function, I keep getting this annoying typescript underline error on map method. I have gone through all fixing possibilities but could not resolve it. The request actually works fine and pulls data, but I just need to get rid of the error. Any suggestion?

 export const getServerSideProps: GetServerSideProps = async () => {

  const { data } = await api.get("/users/index", { //axios api
    params: {
      _limit: 12
      _sort: "created_at", 
      _order: "desc"
    }
  })

  
  const users = data.map(user => { // <-error line under map method
    return {
      id: user.id,
      name: user.name,
      created_at: user.created_at,
  
    }
  });

Upvotes: 4

Views: 16335

Answers (1)

Josh
Josh

Reputation: 682

I think in either 0.22 or 0.23 of axios they changed the Typescript signature so now you have to cast data see the changelog for more information. To resolve this you can pass a generic:

type User = {
   id: string
   name: string
   created_at: string
}

const { data } = await api.get<User[]>("/users/index", { //axios api
    params: {
      _limit: 12
      _sort: "created_at", 
      _order: "desc"
    }
})

Else you could just typecast in situ:

const users = (data as User[]).map(user => { // <-error line under map method
    return {
      id: user.id,
      name: user.name,
      created_at: user.created_at,
  
    }
  });

Upvotes: 8

Related Questions