Next.js Discord

Discord Forum

API calling

Unanswered
Pacific saury posted this in #help-forum
Open in Discord
Pacific sauryOP
Hi, I need help with my API calls. I'm trying to have a 2 text boxes and then a submission box that adds the information in the text boxes to a databse thats formatted like so
CREATE TABLE IF NOT EXISTS Reviews ( ReviewID SERIAL PRIMARY KEY, Approved varchar(10), Name varchar(50), Review varchar(1000) );
any help with how I should go about this would be very helpful. I think i need to do useState but you guys would know better than me. I'll provide my create-review method as well.

import { sql } from '@vercel/postgres'; import { NextResponse } from 'next/server'; export async function GET(request: Request) { try { await sql
CREATE TABLE IF NOT EXISTS Reviews (
ReviewID SERIAL PRIMARY KEY,
Approved varchar(10),
Name varchar(50),
Review varchar(1000)
);
; const reviews = await sqlSELECT * FROM Reviews;; return NextResponse.json({ reviews }, { status: 200 }); } catch (error) { return NextResponse.json({ message: 'An error occurred', error: String(error) }, { status: 500 }); } }

64 Replies

@Pacific saury firstly it's not a get request, you are updating the db via stuff from the request so POST request



There are a lot of ways to do forms in nextjs, check out https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations
so ill change it to POST
Black-throated Blue Warbler
are you on the latest next.js? Sounds like a good use case for a Server Action since you are mutating data.
whats server action
@Pacific saury whats server action
Black-throated Blue Warbler
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations New way to mutate data without needing to create an internal api route
Black-throated Blue Warbler
hard to say, you only posted your GET api handler, no idea what you're trying to do 😄
are you working with a form?
Pacific sauryOP
well i was thinking that i probably should
since its like
text boxes
Black-throated Blue Warbler
yea your description sounds like a form. on submit creates tables based on input values
Pacific sauryOP
create a table?
Black-throated Blue Warbler
well, shouldn't it be creating a record in the table? instead of creating the table
Pacific sauryOP
yeah
Black-throated Blue Warbler
you are using create table

      CREATE TABLE IF NOT EXISTS Reviews (
        ReviewID SERIAL PRIMARY KEY,
        Approved varchar(10),
        Name varchar(50),
        Review varchar(1000)
      );
Pacific sauryOP
the top was just showing the format i was using for the table
and then below
i have what im using to add to the table
import { sql } from '@vercel/postgres'; import { NextResponse } from 'next/server'; export async function GET(request: Request) { try { await sql CREATE TABLE IF NOT EXISTS Reviews ( ReviewID SERIAL PRIMARY KEY, Approved varchar(10), Name varchar(50), Review varchar(1000) ); ; const reviews = await sqlSELECT * FROM Reviews;; return NextResponse.json({ reviews }, { status: 200 }); } catch (error) { return NextResponse.json({ message: 'An error occurred', error: String(error) }, { status: 500 }); } }
idk how you posted the code like that
Black-throated Blue Warbler
i'm, not very familiar with vercel or postgres but it seems wrong. you only need to create the reviews table 1 time.

I don't see anything that would add a record to that reviews table
Pacific sauryOP
wait
i think
i sent the wrong code
☠️
WAIT I DID
HOLD ON
WAITTTT
Black-throated Blue Warbler
three tilds and the language, so ```js
ahh
ok
Black-throated Blue Warbler
<code here>
err
Pacific sauryOP
import { sql } from '@vercel/postgres';
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get('name');
  const review = searchParams.get('review');

  try {
    if (!name || !review) throw new Error('Name and Review required');
    await sql`
      INSERT INTO reviews (approved, name, review)
      VALUES ('denied', ${name}, ${review});`;
  } catch (error) {
    return NextResponse.json({ error }, { status: 500 });
  }
}
im gonna change this to post rq
Black-throated Blue Warbler
yea no thats not what you wnat.
Pacific sauryOP
oh...
LOL
Black-throated Blue Warbler
could do something like this:

import { sql } from '@vercel/postgres'; // Adjust according to your SQL client

export default function Page() {
  // Server action to handle form submission and insert a record into the Reviews table
  async function handleAddReview(formData: FormData) {
    'use server';

    // Extract form data
    const approved = formData.get('approved');
    const name = formData.get('name');
    const review = formData.get('review');

    // Insert the form data into the Reviews table
    await sql`
      INSERT INTO Reviews (Approved, Name, Review) 
      VALUES (${approved}, ${name}, ${review});
    `;
  }

  return (
    <form action={handleAddReview}>
      <div>
        <label htmlFor="approved">Approved:</label>
        <input type="text" id="approved" name="approved" required />
      </div>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" name="name" required />
      </div>
      <div>
        <label htmlFor="review">Review:</label>
        <textarea id="review" name="review" required></textarea>
      </div>
      <button type="submit">Submit Review</button>
    </form>
  );
}
Pacific sauryOP
howd you do that so fast wtf
Black-throated Blue Warbler
That is an untested response from ChatGPT
Pacific sauryOP
ah
ah and it uses the server action as well
Black-throated Blue Warbler
Be warned ChatGPT does not know much about server actions 😄
Pacific sauryOP
LOL
Black-throated Blue Warbler
you have to explain it first and give examples if you want a response like above
Pacific sauryOP
ok but since the approved is like
defaulting to a value in my add review
i should remove it from the form
right
Black-throated Blue Warbler
but server actions are cool because you don't have to write a post request handler, you can use private env variables right in the server action and it won't be exposed to the client
Black-throated Blue Warbler
well it doesn't look like you are using env variables at the moment, but most people store secrets there. Like database username & password, you can use those variables safely in server actions
Pacific sauryOP
i have a .env.local file if thats what you mean
Black-throated Blue Warbler
yea that would be for your localhost secrets, .env for production

https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables
that way you dont expose sensitive information like your database password in your code
you can read those variables directly in your server action
Pacific sauryOP
ok fire im gonna play around with this a little and then probably get stuck in a bit
thanks @Black-throated Blue Warbler