Next.js: Advise on how to do two seperate API calls on the same Page?

Created on 29 Apr 2019  路  1Comment  路  Source: vercel/next.js

Hi, I have a question. Excuse me for my naivety but I'm very new to Javascript and the React/Next world in general. Winging it from the PHP world, where things seem to be a-lot easier for me.

I have a page called Mods.js, which is based off the blog example from the Next documentation. Inside the blogs page I'm also wanting to display prices related to the current mod. My only idea on how to achieve this is to do two seperate API calls - one two the mods API endpoint and one to the prices API endpoint.

Is this the way I should be going?

import Header from '../components/Header'
import MetaData from '../components/MetaData'
import fetch from 'isomorphic-unfetch'
import Link from 'next/link'
import "../style.css"


const Mod = props => (
  <div>

    <body className="bg-dark">
      <Header/>
      <MetaData/>

      <div className="container">

      <Link as={`/`}><a className="btn btn-primary mb-5">Home</a></Link>

        <h5 className="text-muted">{props.modsData.brand}</h5>
        <h1>{props.modsData.battery}</h1>






      </div>

   </body>
  </div>
)


//https://alligator.io/react/axios-react/
Mod.getInitialProps = async function(context) {
    const { id } = context.query
    const res = await fetch(`http://localhost:1337/mods/${id}`)
    const modsData = await res.json()

    return { modsData }
  }

export default Mod

Most helpful comment

Hi @m113t! Thanks for reaching out -- our Spectrum tends to be the best place for these types of questions!

While I'm here though, you should be able to call two different APIs in your getInitialProps without problem. Make sure to use Promise.all instead of two separate awaits so the calls happen at the same time!

Something along these lines:

Mod.getInitialProps = async function(context) {
  const { id } = context.query;

  const [modsData, priceData] = await Promise.all([
    fetch(`http://localhost:1337/mods/${id}`).then(r => r.json()),
    fetch(`http://localhost:1337/prices/${id}`).then(r => r.json())
  ]);

  return { modsData, priceData };
};

Good luck!

>All comments

Hi @m113t! Thanks for reaching out -- our Spectrum tends to be the best place for these types of questions!

While I'm here though, you should be able to call two different APIs in your getInitialProps without problem. Make sure to use Promise.all instead of two separate awaits so the calls happen at the same time!

Something along these lines:

Mod.getInitialProps = async function(context) {
  const { id } = context.query;

  const [modsData, priceData] = await Promise.all([
    fetch(`http://localhost:1337/mods/${id}`).then(r => r.json()),
    fetch(`http://localhost:1337/prices/${id}`).then(r => r.json())
  ]);

  return { modsData, priceData };
};

Good luck!

Was this page helpful?
0 / 5 - 0 ratings