Home > Software engineering >  Pass parameters of a form to a REST API in React
Pass parameters of a form to a REST API in React

Time:11-27

I have a REST API and I want to pass multiple value of a form like parameters using JavaScript and ReactJS when I submit the data.

my problem is send the values of forms in React Hook Forms

This is my API:


const URL = 'https://localhost:8000'

export const FetchRewards = async (id, serial) => {

 const res = await axios.get(`${URL}/api/public/validate_ticket?serial=${serial}&ticket_id=${id}`);
 if (res.status !== 200) return [];

 return res.data;
};

This my component:

import { React, useEffect, useState } from 'react'
import { useForm } from "react-hook-form"
import { FetchRewards } from '../services/consultAPI'


export default function RequestModule() {
  
  const [Ticket, setTicket] = useState(null);
  const [Res, setRes] = useState(null);
  const [TicketDate, setTicketDate] = useState(null);
  const [Rewards, setRewards] = useState([]);
  const [status, verifyStatus] = useState(null)
  const [existRewards, setExistRewards] = useState(false);

const getData = async(id, serial) => {
    const data = await FetchRewards(id, serial);
    setRes(data);
    setTicketDate(data.ticket.fecha_juega);
    setRewards(data.premios);
    setTicket(data.ticket.ticket);
    verifyStatus(data.ticket.status);
    setExistRewards(true);
  }

  useEffect(()=>{
    if(!existRewards) getData();
  },[existRewards])

const{
    register, 
    handleSubmit,
    formState: { errors }
  } = useForm();

  const onSubmit = (data) => {
    console.log(JSON.stringify(data.id))
    console.log(JSON.stringify(data.Serial))
  };

  const petitionRequest = () => {
    <div className="consulta">
      <img src={bgConsulta} alt="consulta"/>
    </div>
  }
  console.log(onSubmit)
  return (
     <form onSubmit={handleSubmit(onSubmit)}>
       <label>
          <p className="mini-text padd">ID</p>

          <input {...register("id", { required: true, maxLength: 16 ,pattern: /^\d $/g })} className="form-control" type="text" placeholder="ID"/>

          {errors.id?.type === 'pattern' && <p className="errortext"><i className="fas fa-exclamation-circle"></i> Only accept numbers</p>}
          {errors.id?.type === 'required' && <p className="errortext"><i className="fas fa-exclamation-circle"></i> Required</p>}

           <div className="spacing"><p className="mini-text">Last 5 digits of Serial</p>

           <input {...register("Serial", { required: true, maxLength: 5, minLength: 5, pattern: /^\w $/g })} className="form-control" type="text" placeholder="Serial"/></div>

           {errors.Serial?.type === 'pattern' && <p className="errortext"><i className="fas fa-exclamation-circle"></i> Onlt text and numbers</p>}
           {errors.Serial?.type === 'maxLength'  && <p className="errortext"><i className="fas fa-exclamation-circle"></i> Only 5 numbers</p>}
           {errors.Serial?.type === 'minLength'  && <p className="errortext"><i className="fas fa-exclamation-circle"></i> Only 5 numbers</p>}
           {errors.Serial?.type === 'required' && <p className="errortext"><i className="fas fa-exclamation-circle"></i> Required</p>}
              
              <div className="spacing">
                <button className="btn btn-success submitbtn" type="submit">
                  SEND
                </button>
              </div>
              </label>
            </form>
);

In the arrow function of onSubmit console return the ID in a string and the SERIAL in string too, but my problem is trying to pass those values as parameter in the function FetchRewards(id, serial), I trying to do with onClick in the Submit Button, but it returns: xhr.js:210 GET https://localhost:8000/api/public/validate_ticket?serial=undefined&ticket_id=undefined 500 (Internal Server Error) when I click the button

CodePudding user response:

Try changing the onSubmit of the form

Yours

<form onSubmit={handleSubmit(onSubmit)}>

To

<form onSubmit={() => handleSubmit(onSubmit)} />

Or maybe just

<form onSubmit={handleSubmit} />

Seems really strange to have a function executing that way, being that you have to provide a callback function, not code to execute.

CodePudding user response:

The answer for the problem was:

const onSubmit = (data) => {
   getData(data.id, data.Serial)
}
  • Related