skip to Main Content

I have a parent component containing a child component with a form. I want to get the data from the form and upload it to the database but I just cannot figure out how.
Here is my code for the child component

"use client"

import React, { useState } from 'react';

function AddProduct(func) {
    const [id, setId] = useState('');
    const [name, setName] = useState('');

    const handleIdChange = (e) => {
        setId(e.target.value);
    };

    const handleNameChange = (e) => {
        setName(e.target.value);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log(`Product added: ID ${id}, Name ${name}`);
        func(id,name);
        //func(id,name);
        // Here you could send this data to your server or handle it some other way
    };

    return (
        <form onSubmith={handleSubmit} className=" card space-y-4">
            <div>
                <label htmlFor="id" className="block text-sm font-medium text-gray-700">
                    ID
                </label>
                <input 
                    type="text"
                    id="id"
                    value={id}
                    onChange={handleIdChange}
                    className="mt-1 block w-full py-2 px-3 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
            </div>
            <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-700">
                    Name
                </label>
                <input
                    type="text"
                    id="name"
                    value={name}
                    onChange={handleNameChange}
                    className="mt-1 block w-full py-2 px-3 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
            </div>
            <button type="submit" className="w-full py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                Add Product
            </button>
        </form>
    );
}

export default AddProduct;


and here’s the code for the parent component

"use server";

import Sidebar from '@/components/Sidebar';
import Link from 'next/link';
import { redirect } from 'next/navigation';
import SignOut from 'src/components/SignOut';
import createClient from 'src/lib/supabase-server';
import RootLayout from '../layout';
import ProductsTable from '@/components/dashboardComponents/ProductsTable';
import AddProduct from '@/components/dashboardComponents/AddProducts';

export default async function Products() {
  const supabase = createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();


  let { data } = await supabase.from('products').select();

  async function func(id1,name1){
    "use server";
    console.log("started uploading data");
    console.log(id1);
    const { data, error } = await supabase
      .from('products')
      .insert([
        { id: id1, name: name1, customer_id: '1' },
      ])
      console.log("done uploading data");
      console.log(error);

};


  return (
    <div>
    <ProductsTable data={data} ></ProductsTable>
    <AddProduct func={func()}></AddProduct>
    </div>
  );
}

This is calling the function but the data isn’t being passed, not sure what else to try, I tried prop drilling but it didn’t work because useState cant be used on the server. Is this the only way to create global props?

2

Answers


  1. Kindly pass the function reference as a prop not the function call.

    The code in parent component should look like this.

    return (
        <div>
        <AddProduct func={func}></AddProduct>
        </div>
      ); 
    
    Login or Signup to reply.
  2. You don’t have to use use server things. You just use API calls in your Client Component.

    Try This:

    In client Component

        const handleSubmit = async (event) => {
         event.preventDefault();
         const request = await fetch("/api/dataEntry",{
         headers: {content-type: "application/json"},
         body: JSON.stringify({ id, name })
         method: "POST"
    });
         const response = await request.json();
         
         if(!response) return alert("Data is not entered")
         else{
         alert("Data Save Successfully");
    }
        };
    
    

    Now create a folder which path is app/api/dataEntry and create a file name route.js/route.ts

    In route.js/route.ts file

    export default function POST(request, response) {
     const {id, name} = await request.json();
     // Now you have your `id` and `name` on server.
    
    // Your can write your server code here which store the data into database.
    
    // but in the last you need to add this.
    
            return new Response(JSON.stringify("enter_your_data_which_you_need_to_return_on_client"), {
                headers: {
                    "content-type": "application/json; charset=UTF-8",
                },
            });
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search