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

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

tomtomdu73 profile image Thomas Cosialls Updated on ・1 min read

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
    }
  }
}

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()
}

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
}

and in your getStaticPros function :

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

Best!

Posted on by:

tomtomdu73 profile

Thomas Cosialls

@tomtomdu73

Web entrepreneur, blockchain enthusiast and adrenaline seeker

Discussion

pic
Editor guide