How to return a message to the Fronteend after checking an API in Reactjs

Asked

Viewed 45 times

-1

I am making a registration form in Nextjs, working ok, the inputs takes the user input data via reactJS FETCH API and sends to a MYSQL database, Until here ok, what I’m cracking my head is time to check and return this check to my frontend before actually recording in the bank.

For example: before INSERT I have to check if you no longer have any record registered to the one being inserted.

My fetch where you take input data and send it to me api

async function handleSubmitPF(data, { reset }) {
  console.log(data)
  try {
    const schema = Yup.object().shape({
      cpf: Yup.string()
      .required('Campo obrigatório'),
      
      name: Yup.string()
      .min(3, 'No mínimo 11 numero para CPF')
      .required('Campo obrigatório'),

      email: Yup.string()
      .email('Digite um email valido')
      .required('Email é obrigatório'),

      celular: Yup.string()
      .required('Campo celular obrigatório'),

    });

    await schema.validate(data, {
      abortEarly: false,
    });

    const res = await fetch('/api/post-pf', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: data.name,
        email: data.email,
        cpf: data.cpf,
        celular: data.celular,
      }),
    })

    setSubmitting(false)
    const json = await res.json()
    if (!res.ok) throw Error(json.message)
    Router.push('/')
    formRef.current.setErrors({});
    reset();

  } catch (err) {
    if(err instanceof Yup.ValidationError){
      const errorMessages = {};
       
      err.inner.forEach(error => {
        errorMessages[error.path] = error.message;
      })
      formRef.current.setErrors(errorMessages);
    }else
    throw Error(err.message)
  }
}

in the pages/api

const handler = async (req, res) => {

const {name,email,cpf} = req.body

  try {
      if(!name || !email  || !cpf) {
      return res
      .status(400)
      .json({ message: ` {${name}/ ${email}/ ${cpf}} are both required`})
        
    }
    
    const sqlConsut = await query(
      `
        SELECT COUNT(*) verificar from cad_empresa where cli_documento = ?
      `,
      [filter.clean(cpf)]
      ); 
   
      var verif =JSON.stringify(sqlConsut);
      console.log(verif);
      
      var json =  JSON.parse(verif);

      console.log(json[0].verificar)

      if(json[0].verificar == 1 ){
    
        return ?

     }
      
      else{
        const sqlInsert = await query(
          `
           INSERT INTO cad_empresa (cli_nome, cli_documento, cli_email) VALUES (?, ?, ?)
          `,
      
          [filter.clean(name),filter.clean(cpf),filter.clean(email)]
        );
        return res.json(sqlInsert);
      }
  } catch (e) {
    res.status(500).json({ message: e.message  });

  }
};

export default handler;

In this api is recording the ok data in the local database on my machine, I have no idea how to return in if There is an alert or a message to the frontend saying that "CPF JA CADASTRADO" if the check is equal to 1. need that when the user sends the request check and return to the frontend a message or a modal if there is already a registered Cpf in the database.

by mysql I already have my query where to check this and it returns 0 if I do not have and write to the bank otherwise if the condition is 1 then I have to return a message to my frontend saying I already have a registration I have no idea how to do :(.

Any hint is welcome, since thank you for the attention.

1 answer

0

I’ll try to explain over a Functional Component.

The first thing you should do is create a state for your application, let’s say it’s just a text.

First you must import the useState:

import { useState } from 'react'

Then you will instantiate in your application:

const [ existsCPF, setExistsCPF ] = useState()

Is the variable existsCPF which you will use to display in your application. Simply insert it using { existsCPF } that it will appear in the application (in this case, the useState() is empty, so for now nothing appears).

Then, when you request in the API, you will change the type value like this:

setExistsCPF('CPF JA CADASTRADO')

React will already worry about updating the component and display it to you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.