1

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

2
  • I may misunderstand your question but are you trying to fetch the data? Something like this: fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json()).then(json => console.log(json)), but in TypeScript? Commented Jun 19, 2020 at 13:10
  • @Hangindev Yes I have been trying to do just that. I am quite new to this, my bad. Commented Jun 19, 2020 at 14:03

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.