Sabrina Reyes
Sabrina Reyes

Reputation: 139

How to parse JSON url with NextJS + TypeScript and display information?

So I have been researching everywhere for this but wasn't able to reach a sensible conclusion. I imported { useRouter } from next/router and successfully parsed a local JSON file, but I would like to parse a JSON object from a URL. Here is one URL for example: http://time.jsontest.com/

I feel like I have tried everything but failed... Basically I am using Shopify API and want to access our database of customers from a JSON for a Dashboard. We are experimenting with NextJS and TypeScript right now, but I don't know. I find it tedious. I just need one example or resource that can help me..

Upvotes: 1

Views: 2744

Answers (1)

Kevin Kirsten Lucas
Kevin Kirsten Lucas

Reputation: 91

If you want to use the data obtained from a JSON object from a URL with the Next.JS api-routes with TypeScript in your API response, you can do this:

import type { NextApiRequest, NextApiResponse } from 'next'

interface Time {
  date: string;
  milliseconds_since_epoch: number;
  time: string;
}

export default async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method !== 'GET') {
    res.status(500).json({message: 'Desculpe, só aceitamos solicitações GET '});
  } else {
    const response = await fetch('http://time.jsontest.com/');
    const data: Time = await response.json();
    res.status(200).json({
      'date': data.date,
      'time in ms': data.milliseconds_since_epoch,
      'time': data.time
    })
  }
}

Place this code inside

root/
├── _src
│   └── _pages
│       └── _api
│           └── myApiTest.ts

To test the file, access http://localhost:3000/api/myApiTest

Ps. I'm using nextjs v10.0.8

Upvotes: 2

Related Questions