How to call the Prismic (CMS) API, from a next.js application? In next.js I have had before:
import React from 'react'
import Link from 'next/link'
import 'isomorphic-fetch'
export default class Index extends React.Component {
static async getInitialProps () {
const res = await fetch('https://myAPI_URL')
const json = await res.json()
return { cars: json.results }
}
render () {
return (
<div>
<p>I can see the data {this.props.cars} </p>
</div>
)
}
}
But I would like to use the Prismic development kit as a dependency, as described in their documentation.
npm install prismic-javascript prismic-dom --save
And code for calling Prismic:
const Prismic = require('prismic-javascript');
const apiEndpoint = "https://your-repository-name.prismic.io/api/v2";
const apiToken = "this_is_a_fake_token_M1NrQUFDWUE0RYvQnvv70";
Prismic.getApi(apiEndpoint, {accessToken: apiToken}).then(function(api) {
return api.query(""); // An empty query will return all the documents
}).then(function(response) {
console.log("Documents: ", response.results);
}, function(err) {
console.log("Something went wrong: ", err);
});
But how do I make the Prismic API call work with next.js, inside the getInitialProps? For example:
import React from 'react'
import Link from 'next/link'
import 'isomorphic-fetch'
export default class Index extends React.Component {
static async getInitialProps () {
// fetch Prismic API and return the results
}
render () {
return (
<div>
<p>Showing data fetched from API here</p>
</div>
)
}
}