So like, im making an app using nextjs, where i take input from user (username password and email) from home page, save it to db via mongoose and then display it on other page named dashboard, im able to save data in db as its easy, but i dont know how to fetch it from db and display it in dashboard in div.. the sources on internet are too confusing and gpt isnt helpful at all..
this is my app structureenter image description here
this is my models/inputs.js
import mongoose from "mongoose";
const inputInfo = new mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
})
const Info=mongoose.models.Info || mongoose.model('Info',inputInfo);
export default Info
this is my action/inputs.js
"use server"
import mongoose from "mongoose";
import Info from "../models/inputs";
const getInputs = async (e) => {
await mongoose.connect("mongodb://localhost:27017/logininfo");
if(mongoose.connection.readyState === 1) {
console.log("connected");
}else{
console.log("not connected");
}
const username = e.get("username");
const email = e.get("email");
const password = e.get("password");
const data = {
username,
email,
password
}
console.log(data);
const userExists= await Info.findOne({username});
if(userExists) {
console.log("user exists");
}else{
const newUser = new Info(data);
await newUser.save();
console.log("new user created");
}
}
export default getInputs;
this is my api/fetchInfo.js
// api/fetchinfo.js
"use server"
import mongoose from "mongoose";
import express from 'express';
import bodyParser from 'body-parser';
import Info from '../models/input';
const app = express();
const port = 3000;
// Middleware to parse JSON bodies
app.use(bodyParser.json());
// Middleware to handle CORS
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// Route to fetch information
app.get('mongodb://localhost:27017/logininfo', async (req, res) => {
await mongoose.connect("mongodb://localhost:27017/logininfo");
if(mongoose.connection.readyState === 1) {
console.log("connected");
} else {
console.log("not connected");
}
});
app.post('mongodb://localhost:27017/logininfo', async (req, res) => {
await mongoose.connect("mongodb://localhost:27017/logininfo");
if(mongoose.connection.readyState === 1) {
console.log("connected");
} else {
console.log("not connected");
}
try {
const data = await Info.create(req.body);
res.json(data);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
})
// Start the server
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
this is my dashboard/page.js
// app/dashboard/page.js
"use client"
import React, { useState, useEffect } from 'react';
const Dashboard = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch("http://localhost:3000/api/fetchinfo")
.then((res) => {
if (!res.ok) {
throw new Error('Network response was not ok');
}
return res.json();
})
.then((data) => {
setData(data);
setLoading(false);
})
.catch((error) => {
setError(error);
setLoading(false);
});
}, []);
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div>
{data ? data.map((item, index) => (
<p key={index}>{item.username} - {item.email}</p>
)) : <p>No data found</p>}
</div>
);
}
export default Dashboard;
i was expecting it to display data but sadly it didnt work, im able to save it properly but displaying is 🙁