-1

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 :(

2
  • 1
    can you be more specific about 'it didnt work'? Are you getting an empty page/ an error message/wrong data? Commented Aug 6, 2024 at 8:56
  • yes, so like when im visiting api/fetchInfo page, its showing page not found, so maybe its not fetching data from mongodb, so how to fetch it :( Commented Aug 6, 2024 at 9:25

1 Answer 1

-1

The Problem seems to be in api/fetchInfo.js as you are using next.js you can create a server without express easily by making a directory getdata/route.js in simple words do same things you did while creating dashboard and set name route inplace of page and paste the following code there:

import mongoose from "mongoose";
import Info from '../models/input';
import { NextResponse } from "next/server";

export async function GET(request) {
    await mongoose.connect("mongodb://localhost:27017/logininfo");
    let alldocuments = await Info.find({});
    NextResponse.json(alldocuments)
}

you can access that array of data by making fetch request at "http://localhost:3000/getdata"

Updated:

// 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/spy")
            .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;

or if you want same stuff in express but i recommend you to use next server for convenience although replace this app.get function:

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");
    }
let alldata = await Info.find({})
res.json(alldata)
  
});

done only two lines are missing.

Sign up to request clarification or add additional context in comments.

1 Comment

bro if you don't know how to read that's not my problem because this is the answer and it is perfectly working. I have also given you an easy approch so don't be foolish to downvote my answer actually that's my fault to answer you. By the way this is the correct answer you can ask anyone about that i think you are not interested in this and just posted the question and when someone answers it you ignored and downvoted it.Fool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.