DEV Community

Cover image for Fixing error : Typescript res.json() is not a function
Thomas Cosialls
Thomas Cosialls

Posted on • Edited on

Fixing error : Typescript res.json() is not a function

The issue

You have finished the great NextJS tutorial and you are now ready to use your fresh knowledge into your next web app project.

You are using getStaticProps function to fetch data from your own NodeJS powered API or from an external API like Airbnb, Facebook, Google before pre-rendering the page.

You have the following code in your index.js page for instance :

import {getIndexData} from 'lib/api.js'

export async function getStaticProps() {
  const indexData = await getIndexData()

  return {
    props: {
      indexData
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

And the following content in lib/api.js :

import axios from 'axios'

const get = endpoint => axios.get(`endpoint`);

export async function getHomeData()
{ 
  const res = await get(`https://api.facebook.com/...`);
  return res.json()
}
Enter fullscreen mode Exit fullscreen mode

It should work fine as mentioned on NextJS but instead, you get this annoying error when you open localhost:3000

Alt Text

The fix

Rewrite your functions the following to start using your data:

In lib/api.js :

export async function getHomeData()
{ 
  const {data: response} = await get(`https://api.facebook.com/...`);
  return response
}
Enter fullscreen mode Exit fullscreen mode

and in your getStaticPros function :

export async function getStaticProps() {
  const data = await getIndexData()
  return {
    props: {
      indexData: data
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Best!

Top comments (0)