Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

52
Views
How to use a third-party API inside next/api?

I am new to NEXTJS and creating a weather application .I am using a openweather api but how can I use it inside the next/api. I had tried by creating a file today.js inside next/api and wrote the code it in this way but I am unable to get data in console ?

today.js

const apikey = process.env.REACT_APP_API_KEY_1;
const url = `https://api.openweathermap.org/data/2.5/weather?q=Bhopal&appid=${apikey}`;

const fecthInfo = async() => {
    const response = await fetch(url);
    const data = await response.json() ;
    return data;
}
export default function handler(req, res) {
    const result = fecthInfo();
    console.log(result)
    res.status(200).json(result)
  }

Can you tell the mistake I am doing , or I have to simply use the fetch method in any component like in reactJS.

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

Looks like you are missing an async/await. This should work:

const apikey = process.env.REACT_APP_API_KEY_1;
const url = `https://api.openweathermap.org/data/2.5/weather?q=Bhopal&appid=${apikey}`;

const fetchInfo = async() => {
    const response = await fetch(url);
    const data = await response.json();
    return data;
};

export default async function handler(req, res) {
    const result = await fetchInfo();
    console.log(result);
    res.status(200).json(result);
}
7 months ago · Juan Pablo Isaza Report

0

Instead of fetching data from a remote api inside the api route. I suggest to use the getServerSideProps() in the route page directly so you have to fetch the data just once.

You pass the requested data through props to the Test component.

const Test= function({data}){
 console.log(data)
 return <div></div>
}



export default async function 
getServerSideProps(){
const response = await fetch(url);
const data = await response.json();
 return {
  props:{data}
 }
}

 export default Test; 
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs