i created a cluster in mongodb atlas it had some dummy data like this
“sample_mflix(movies(title, runtime, year))”
and i want to display it on a table, here is the code for the component that do the display:
import React, { useState, useEffect } from 'react'
interface Movie{
_id:any
title: string
year:number
runtime: number
}
function DataTable() {
const [movies, setMovies] = useState<Movie[]>([])
useEffect(()=>{
async function fetchMovies() {
try {
const response = await fetch('/api/movies')
if(!response.ok){
console.log(response)
}
const data: Movie[] = await response.json()
setMovies(data)
} catch (error) {
console.error('failed to fetch',error)
}
}
fetchMovies()
}, [])
return (
<div className="p-4">
<h1 className="text-2xl font-bold mb-4">Movie List</h1>
<div className="overflow-x-auto">
<table className="table-auto w-full border-collapse border border-gray-300">
<thead>
<tr className="bg-gray-200">
<th className="border border-gray-300 px-4 py-2 text-left">Title</th>
<th className="border border-gray-300 px-4 py-2 text-left">Year</th>
<th className="border border-gray-300 px-4 py-2 text-left">Runtime</th>
</tr>
</thead>
<tbody>
{movies.map((movie, index) => (
<tr key={index} className="even:bg-gray-100">
<td className="border border-gray-300 px-4 py-2">{movie.title}</td>
<td className="border border-gray-300 px-4 py-2">{movie.year}</td>
<td className="border border-gray-300 px-4 py-2">{movie.runtime}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
export default DataTable
this is the db connetion :
import { config } from 'dotenv';
config();
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
throw new Error('Please define the MONGODB_URI environment variable');
}
interface Cached {
conn: typeof mongoose | null;
promise: Promise<typeof mongoose> | null;
}
let cached: Cached = (global as any).mongoose;
if (!cached) {
cached = (global as any).mongoose = { conn: null, promise: null };
}
async function connectToDatabase() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
cached.promise = mongoose.connect(MONGODB_URI as string).then((mongoose) => {
return mongoose;
});
}
cached.conn = await cached.promise;
return cached.conn;
}
export default connectToDatabase;
and this is the api/movies.ts :
import type { NextApiRequest, NextApiResponse } from 'next';
import connectToDatabase from '../../utils/db';
import mongoose, { Document, Model } from 'mongoose';
interface IMovie extends mongoose.Document {
title: string
year:number
runtime: number
}
// Define a schema for movies
const movieSchema = new mongoose.Schema({
title: { type: String, required: true },
year: { type: Number, required: true },
releaseYear: { type: Number, required: true },
});
// Create a model for movies
const Movie: Model<IMovie> = mongoose.models.Movie || mongoose.model<IMovie>('Movie', movieSchema);
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
await connectToDatabase();
try {
const movies = await Movie.find({});
res.status(200).json(movies);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch movies' });
}
}
ive tried everything but two errors keeps poping up
D:web dev 2next-te…tsdataTable.tsx:17
GET http://localhost:3000/api/movies 404 (Not Found)
fetchMovies @ D:web dev 2next-te…tsdataTable.tsx:17
DataTable.useEffect @ D:web dev 2next-te…tsdataTable.tsx:27
and this one:
failed to fetch SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
the response.ok = false