Open ChenBingWei1201 opened 4 months ago
By the way, I learn the react-query from this video of building up a food ordering app
these are the snippets generated by ChatGPT 3.5 for demo only
// server.ts
import express, { Request, Response } from 'express';
import cors from 'cors';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient(); const app = express();
app.use(express.json()); app.use(cors());
interface Post { id: number; title: string; content: string; }
// Get all posts app.get('/api/posts', async (req: Request, res: Response<Post[]>) => { const posts = await prisma.post.findMany(); res.json(posts); });
// Create a new post
app.post('/api/posts', async (req: Request, res: Response
// Update a post
app.put('/api/posts/:id', async (req: Request, res: Response
// Delete a post app.delete('/api/posts/:id', async (req: Request, res: Response<{ message: string }>) => { const { id } = req.params; await prisma.post.delete({ where: { id: parseInt(id) }, }); res.json({ message: 'Post deleted' }); });
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(Server running on port ${PORT}
);
});
- frontend:
```typescript
// src/components/PostList.tsx
import React from 'react';
import { useQuery } from 'react-query';
interface Post {
id: number;
title: string;
content: string;
}
async function fetchPosts(): Promise<Post[]> {
const response = await fetch('/api/posts');
if (!response.ok) {
throw new Error('Failed to fetch posts');
}
return response.json();
}
function PostList() {
const { data: posts, isLoading, isError } = useQuery<Post[]>('posts', fetchPosts);
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error fetching posts</div>;
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
))}
</div>
);
}
export default PostList;
I decied to use apollo graphql
Maybe I will try to use express & prisma for backend and react-query for frontend, because some unknown problems occurred when I built up my wp final project with apollo server and apollo client. Most of them violate the Rules of Hooks. I haven't found any solution to it.