logologo

Three-D

☕Sign in

    Recent Post:

    featured post image

    snippets

    featured post image

    What is Currying?

    featured post image

    What is an IIFE?

    Categories:

    nextjsjavascriptthreejshonoreactjs

    Interacting with Databases- Next.js , Async/Await

    July 1, 2024

    476

    image

    Think you know it all?

    Take quiz!

    One of the advantages of Next.js is the ability to interact with your database directly within your application, bypassing the need for separate API layers. Here’s how to do it:

    1. Setting Up Database Connection

    First, set up a connection to your database. This example uses MongoDB.

    // lib/db.js import { MongoClient } from 'mongodb'; const client = new MongoClient(process.env.MONGO_URL); export async function connectToDatabase() { if (!client.isConnected()) await client.connect(); return client.db('mydatabase'); }

    2. Fetching Data

    Fetch data directly within your Next.js pages or components using the connectToDatabase function.

    code

    // pages/index.js
    import { connectToDatabase } from '../lib/db';
    
    export async function getServerSideProps() {
     const db = await connectToDatabase();
     const posts = await db.collection('posts').find().toArray();
    
     return {
      props: {
       posts: JSON.parse(JSON.stringify(posts)),
      },
     };
    }
    
    export default function HomePage({ posts }) {
     return (
      <div>
       <h1>Posts</h1>
       <ul>
        {posts.map(post => (
         <li key={post._id}>{post.title}</li>
        ))}
       </ul>
      </div>
     );
    }

    3. Manipulating Data

    You can also manipulate data directly within your page functions.

    code

    // pages/new-post.js
    
    import { connectToDatabase } from '../lib/db';
    import { useState } from 'react';
    export default function NewPostPage() {
     const [title, setTitle] = useState('');
     async function handleSubmit(event) {
      event.preventDefault();
      const db = await connectToDatabase();
      await db.collection('posts').insertOne({ title }); // Redirect or show success message
     }
     return (
      <form onSubmit={handleSubmit}>
       {' '}
       <input type='text\' value={title} onChange={(e) => setTitle(e.target.value)} placeholder='Post Title\' />{' '}
       <button type='submit\'>Add Post</button>{' '}
      </form>
     );
    }

    By directly interacting with your database using async/await, you can streamline your application and reduce complexity, making your development process more efficient.