I'm trying to fetch data on the client side - using 'use client' to an API route handler in NextJS. I've followed the example to use useEffect
and useState
to prevent looping the fetch request. Instead of rerendering with my unordered list of todos it just loops infinitely.
This is my code
'use client';
import React from 'react';
export default async function Page() {
const [todos, setTodos] = React.useState([]);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
async function getTodos() {
const res = await fetch('/api/todo');
const todos = await res.json();
console.log(todos);
setLoading(false);
setTodos(todos);
}
getTodos();
},[]);
console.log('rendering', loading, todos);
if (loading) return (<p>rendering</p>);
return (
<div className="relative todos-container shadow-xl m-2 rounded-xl w-full">
{/* <h1 className='mb-5'>Todos</h1> */}
<ul className='p-3'>
{todos.map((todo, idx) => {
return (<li className='p-3 my-3 last:mb-0 first:mt-0 bg-slate-100 rounded-lg' key={idx}>{todo.body}</li>)
})}
</ul>
<div className='absolute text-center w-full -bottom-10 left-0'>
<span className='font-extralight text-xs rounded-xl shadow m-2 p-2 bg-slate-100'>shift + enter to submit a new todo item</span>
</div>
</div>
);
}
My API endpoint code:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
export async function GET() {
const todos = await prisma.todo.findMany();
return new Response(JSON.stringify(todos), {
headers: {
'content-type': 'application/json'
}
});
}