How can I query the API with a simple script?

Hi

I'm currently trying to set up a prebuild script in Next.js for my project. I need the script to fetch all blog posts (so I can then feed them in to Algolia).

It will then run every time there is a rebuild triggered by a change to content in Prismic.

I am looking at the documentation here:

I've copied and pasted the code from step 3 (replacing the api endpoint string with a link to my own repo), but am getting the error 'req is not defined' when trying to run the code.

If I remove the req argument from the Prismic.client() function, I get "TypeError: Prismic.client(...).then is not a function".

Probably a really basic error I'm making here, but it's unclear from the documentation what I need to do to fetch the data successfully.

Thanks

Hi @david.al.fox,

We're currently working on updating and simplifying the vanilla JavaScript documentation.

You won't need the req argument in that call. The req argument enables previews in Node.js, and you won't need previews for Algolia.

I can't tell why you would get that error from the information you've provided. Could you share your project files with me so I can take a closer look? (Feel free to send them in a DM.)

A few things you could try:

  • If you're using @prismicio/client v6 (rather than v5), you might get an error like that. You're probably not on v6, as it's still in beta, but you could check.
  • You could try restructuring this using async await, which would look something like this:
const init = async () => {
  const api = await Prismic.client(apiEndpoint)
  console.log(api) // Check to see if things are working
  const response = await api.query("")
  console.log(response)
}

init()

That might also help give you some insight into what's happening.

If you're interested in testing out our new JavaScript documentation and giving feedback, let me know and I can send you a DM to a preview link. (But a heads up, the new docs use @prismicio/client v6, which might mean changing some of your code. v6 does have a method to fetch all docs, which will make your Algolia integration a little easier.)

Sam

Hi Sam

Thanks for your response. I copied and pasted your code over into the file and it seems to be working now. How odd!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.