4

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>
    )
  }
}
userden
  • 1,615
  • 6
  • 26
  • 50

1 Answers1

4

You already have all the components ready to go. Instead of the fetch, await the Prismic request. Then return the results.

import React from 'react';
import Prismic from 'prismic-javascript';

const apiEndpoint = 'https://project.prismic.io/api/v2';
const apiToken = 'TOKEN';

export default class Index extends React.Component {
  static async getInitialProps({ req, query }) {
    const data = await Prismic.getApi(apiEndpoint, { accessToken: apiToken })
      .then(api => {
        return api.query(''); // An empty query will return all the documents
      })
      .catch(err => console.log(err));

    return { cars: data.results };
  }

  render() {
    return <div>Example car id: {this.props.cars[0].id}</div>;
  }
}
Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56
  • @Fabian Schultz How about handling more than 1 promises? How to apply Promise.all() in this case? – vizFlux Oct 14 '17 at 00:42
  • 1
    @vizFlux You can put the promises in several functions and pass that to one `Promise.all`. Check out [some other questions about that](https://stackoverflow.com/a/41292710/6941627), or ask a new one :) – Fabian Schultz Oct 14 '17 at 10:08