Closed4
Astro 2 + React + D1, お試し
概要
Astro 2 + React , Cloudflare D1 試すメモです
- asstro SSR , islands風で、Reactを追加する形です
環境
- Cloudflare D1
- Astro 2.2-
- React: 18.2
- Vercel
関連のコード
- API serverは、前と同じです
React add
npm create astro@latest
#
npx astro add react
- vercel設置する場合、追加インストール必要です。
- todo/index.astro、 clientディレクティブで react追加
- List, add の機能です
- 中間API経由で、 D1に接続します
---
import Layout from '../../layouts/Layout.astro';
import App from './App.tsx';
//
---
<Layout title="Welcome to Astro.">
<main class="container">
<App client:only="react" />
</main>
</Layout>
- todo/App.tsx
App.tsx
import {useState, useEffect} from 'react';
import HttpCommon from '../../lib/HttpCommon';
import CrudIndex from './CrudIndex';
//
let pageItem: any[] = [];
//
function Page () {
const [updatetime, setUpdatetime] = useState<string>("");
//
const updateTimestap = function() {
const dt = new Date().toString();
setUpdatetime(dt);
}
//
useEffect(() => {
(async () => {
getList();
})()
}, []);
/**
*
* @param
*
* @return
*/
const getList = async function() {
try{
const d = await CrudIndex.getList()
pageItem = d;
updateTimestap();
} catch (e) {
console.error(e);
}
}
/**
*
* @param
*
* @return
*/
const createTodo = async function() {
try{
const result = await CrudIndex.addItem();
if(result) {
window.location.reload();
}
} catch (e) {
console.error(e);
}
}
/**
*
* @param
*
* @return
*/
const todoDelete = async function(id: number) {
try{
const result = await CrudIndex.delete(id);
if(result) {
getList();
}
} catch (e) {
console.error(e);
}
}
console.log(updatetime);
//
return (
<div><h3>Todo</h3>
<span className="d-none">{updatetime}</span>
<hr />
<label>Title: <input id="title" className="form-control" /></label>
<button onClick={()=>createTodo()} className="btn btn-sm btn-primary ms-2"
>Create</button>
<hr />
{pageItem.map((item: any ,index: number) => {
return (
<div key={index}>
<h3>{item.title}</h3>
<span>ID: {item.id}, {item.createdAt}</span>
<button onClick={()=>todoDelete(item.id)} className="btn btn-sm btn-outline-danger ms-2"
>Delete</button>
<hr />
</div>
)
})}
</div>
);
}
export default Page;
- GIFアニメ追加しました。アラートカスタムと、自動消去
このスクラップは2023/08/26にクローズされました