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;