Navigating through Notion's API to filter by a specific slug

I'm currently attempting to retrieve a page from a database in Notion using the slug as a filter, but I keep encountering an error. Here is the error message:

@notionhq/client warn: request fail {
  code: 'validation_error',
  message: 'body failed validation. Fix one:\n' +
    'body.filter.formula.string should be defined, instead was `undefined`.\n' +
    'body.filter.formula.checkbox should be defined, instead was `undefined`.\n' +
    'body.filter.formula.number should be defined, instead was `undefined`.\n' +
    'body.filter.formula.date should be defined, instead was `undefined`.'
}

I am using next.js

My controller file is notion.js:


export async function getSingleBlogPost(slug) {
  const database = process.env.NOTION_BLOG_DATABASE_ID ?? '';

  // list of blog posts
  const response = await client.databases.query({
    database_id: database,
    filter: {
      property: 'Slug',
      formula: {
        text: {
          equals: slug, // slug
        },
      },
      // add option for tags in the future
    },
    sorts: [
      {
        property: 'Updated',
        direction: 'descending',
      },
    ],
  });

  if (!response.results[0]) {
    throw 'No results available';
  }

  const page = response.results[0];
  const mdBlocks = await n2m.pageToMarkdown(page.id);
  const post = await pageToPostTransformer(page);
  const markdown = n2m.toMarkdownString(mdBlocks);

  return {
    post,
    markdown,
  };
}

For more code from my file view: https://pastebin.com/RapTGN38

In my [slug].jsx:

import ReactMarkdown from "react-markdown";
import Head from "next/head";

import {getSingleBlogPost, getPublishedBlogPosts} from '../../lib/notion.js'

const Post = ({markdown, post}) => {
    return (
        <>
            <Head>
                <title>{post.title}</title>
                <meta name={"description"} title={"description"} content={post.description}/>
                <meta name={"og:title"} title={"og:title"} content={post.title}/>
                <meta name={"og:description"} title={"og:description"} content={post.description}/>
                <meta name={"og:image"} title={"og:image"} content={post.cover}/>
            </Head>

            <div className="min-h-screen">
                <main className="max-w-5xl mx-auto relative">
                    <div className="flex items-center justify-center">
                        <article className="prose">
                            <ReactMarkdown>{markdown}</ReactMarkdown>
                        </article>
                    </div>
                </main>
            </div>

        </>
    )
}

export const getStaticProps = async (context) => {

    // @ts-ignore
    const p = await getSingleBlogPost(context.params?.slug)

    if (!p) {
        throw ''
    }

    return {
        props: {
            markdown: p.markdown,
            post: p.post
        },
    }
}

export async function getStaticPaths() {

    const posts = await getPublishedBlogPosts()

    // Because we are generating static paths, you will have to redeploy your site whenever
    // you make a change in Notion.
    const paths = posts.map(post => {
        return `/post/${post.slug}`
    })

    return {
        paths,
        fallback: false,
    }
}

export default Post;

While trying to set up my personal blog, I'm encountering this error when opening a post link.

Answer №1

Greetings, Liendo! I hope I have arrived in time to assist you with your issue!

Upon careful examination of the API error message, the solution becomes apparent:

Fix one:\n' +
'body.filter.formula.string should be defined, instead was `undefined`.\n' +
'body.filter.formula.checkbox should be defined, instead was `undefined`.\n' +
'body.filter.formula.number should be defined, instead was `undefined`.\n' +
'body.filter.formula.date should be defined, instead was `undefined`.'

Therefore, within your filter, in the formula section, you must replace text with one of the following attributes (string, checkbox, number, or date) as one of them must be defined. Considering that your slug is of type string, your filter should appear as follows:

filter: {
      property: 'Slug',
      formula: {
        string: {
          equals: slug,
        },
      },
    },

This adjustment should resolve the issue at hand!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to creating fog animations in three.js

I'm attempting to adjust the fog density using tweening, but for some reason, it doesn't seem to be working. Here are my default settings: var camera, densityFog, colorFog2; colorFog2 = 0xfee2ed; densityFog ...

Utilizing react js computed property to retrieve a state value: A guide

I recently developed a fading text component where the header fades in and out using transition opacity CSS and a visibility state. To simplify my code, I decided to create a fading text group component that can handle multiple fading texts at once. My goa ...

Ways to activate javascript following a PHP submission?

It's a bit tricky to explain. function m(val){ var element=document.getElementById('othermethod'); if(val=='others') element.style.display='block'; else element.style.display=&apo ...

At times, MomentJS may miscalculate and add an incorrect number of hours

My goal is to add a specific amount of hours to a 24-hour time, but I'm encountering an issue with the time 00:00. The code I've written works correctly for all times except midnight. For example, if I have 01:30 and add 1 hour, it gives me 02:3 ...

What is the best way to keep JWT secure in a web browser?

Recently, I delved into the world of JSON Web Tokens (JWT) for the first time. I'm currently working on a Node.js application utilizing the Hydra-Express framework. My goal is to implement JWT for authentication purposes. Following the documentation, ...

Using ThreeJs and TweenJS to insert a delay between tweens using a for loop

Struggling with animating a bin packing problem using Three.JS and Tween.JS. I am having difficulty getting the animation to play successively rather than all at once within my loop. Attempting to use the setTimeout solution has not been successful. Does a ...

Unexpected behavior with scrollTop

Note Reopening bounty as I forgot to award it last time. This question has already been answered by Master A.Woff. I am looking for a way to automatically scroll to a specific row when a user expands it, so that the content is immediately visible witho ...

Creating a single row on the Wordpress options page with a colspan in the first row

On my WordPress options page, I am utilizing the Fluent Framework to create fields. This framework is quite similar to Meta Box, as both make use of the do_settings_fields function to generate code like the following: <table class="form-table"> < ...

What is the reason for adding CSS styles to a JavaScript file without importing them?

/Navbar.js/ import './navbar.scss'; import {FaBars, FaSearch} from "react-icons/fa"; import { useState } from 'react'; function Navbar(){ const [hide,sethide] = useState(true); const barIcon = document.querySelectorAl ...

How can we ensure the discord client object is easily accessible within event files?

I'm a beginner with Discord.js and I've been trying to figure out how to allow event and command files to access the main client instance. I want to be able to call client.database in an event file for CRUD operations, but I'm confused on ho ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Leveraging external JavaScript libraries in SAPUI5

I'm currently facing an issue while trying to include an external .js file in my SAPUI5 Controller. jQuery.sap.includeScript("externalLibrary.min.js", function() { // initializing objects from the library }); Despite setting up ...

Guide for accessing Javascript documentation via console?

There are many times when I am coding in Python, that I find myself wanting to quickly access the documentation for a function. In the iPython console, I can easily do this by entering dir?? which retrieves the documentation for the dir function. Is ther ...

Tips for looping through client.get from the Twitter API with node.js and express

I am in the process of developing an application that can download a specific number of tweets. For this project, I am utilizing node.js and express() within my server.js file. To retrieve data from the Twitter API, I have set up a route app.get('/ap ...

Tips for effectively implementing correct reselection in a React-Redux application

I have a system that allows users to search for data based on their input. I am currently implementing reselect in my application. import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux" ...

Increment the name field automatically and track the number of auto-increment variables being sent through serialization

I am trying to implement a functionality where users can add more inputs by pressing a button, each representing an additional 'guest'. The issue I am facing is with auto-incrementing the JavaScript so that new inputs are added with an incremente ...

issue with bootstrap modals single firing when using remote data source

I am facing an issue with my table that contains a list of items, each item having a <select> element with different statuses. Here's how the process is supposed to work: Upon changing the status, a modal should pop up. The modal suc ...

What is the best way to toggle DOM classes in React using Material-UI components?

Currently utilizing Material UI alongside React, I have a div element: <div className={classes.div}></div> I am attempting to dynamically add a conditional class to it: <div className={classes.div + divActive ? `${classes.div}__active` : &a ...

Initiate the setInterval function upon clicking the button

Is there a way to successfully start setInterval when the user presses a button with ID #begin? I have attempted various methods, but they all seem to prevent setInterval from working at all. Any suggestions on how to make this work correctly? Thank you! ...

The IE9 confirmation dialog fails to pause for user response, resulting in automatic postback before user input is received

Behind the Scenes btnNext.Attributes.Add("onclick", " return Verification(this,'" + GetLocalResourceObject("message").ToString() + "'); ") .ASPX Page [Within javascript tags] function Verification(source, message) { var dialog = '< ...