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
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 await
s 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!
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 usePromise.all
instead of two separateawait
s so the calls happen at the same time!Something along these lines:
Good luck!