DEV Community

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

Posted on • Edited on

3 3

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay