D1 and Pages binding with React

Hello everyone,

I’m trying to use the D1 database bindings with Pages (like explained in https://developers.cloudflare.com/pages/platform/functions/bindings/#d1-databases). I’m also using React in pages.

I have this but I don’t get any result. I don’t know if that’s possible with React, if so, what am I missing?

Here’s my code:

import React, { useState } from 'react';

function Listing() {
  const [error, setError] = useState(null);
  const [blogArticles, setBlogArticles] = useState([]);

  async function onRequest(context) {
    try {
      const ps = context.env.blogDB.prepare('SELECT * from articles');
      const data = await ps.all();

      const blogArticles = data.map(article => ({
        id: article.id,
        title: article.title,
        content: article.content,
      }));

      setBlogArticles(blogArticles);
    } catch (error) {
      setError(error);
    }
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Blog Articles</h1>
      <ul>
        {blogArticles.length > 0 ? (
          blogArticles.map(article => (
            <li key={article.id}>
              <h2>{article.title}</h2>
              <p>{article.content}</p>
            </li>
          ))
        ) : (
          <li>No blog articles found</li>
        )}
      </ul>
    </div>
  );
}

export default Listing;

Are you trying to do this client side or server side? Also is this plain React, Create React App or a framework?

Thanks for your reply.

I’m trying to do it client side, as it’s in the Pages themselves. From what I understood from the link I shared, this is possible to call the D1 straight from the Cloudflare Pages. It is plain React.

1 Like