简体   繁体   English

React Hook 在单击 2 个不同的按钮时从 APi 获取数据

[英]React Hook to fetch data from APi when click 2 different button

I have create next.js app with using mongoDB as database.我使用 mongoDB 作为数据库创建了 next.js 应用程序。

So, I currently have 2 buttons.所以,我目前有 2 个按钮。 (Delete, Save). (删除,保存)。 I want my application to when click 'Delete' button, it will then use fetch to delete data from mongoDB using APi.我希望我的应用程序在单击“删除”按钮时,然后使用fetch使用 APi 从 mongoDB 删除数据。 Other, click 'Save' button, use fetch to save data to mongoDB using APi as well.其他,单击“保存”按钮,使用fetch将数据保存到 mongoDB 使用 APi 为好。

First, I use document.getElementById('buttons').addEventListener('click', function (evt)) to get to the code to do the letter part of code to where I want.首先,我使用document.getElementById('buttons').addEventListener('click', function (evt))来获取代码以将代码的字母部分执行到我想要的位置。

Then I use the if-else condition to use different fetch on each button based on buttons' id.然后我使用 if-else 条件根据按钮的 id 在每个按钮上使用不同的fetch

But, every time I click 'save' button, it will get alert respond form browser to click 'ok' up to the time that I click save before.但是,每次我点击“保存”按钮时,它都会收到警报响应表单浏览器点击“确定”直到我之前点击保存的时间。 For example, I have click 'save' button with input data of product_name = car and code = 123 after that the alert show up and I have to only click 'ok' one time.例如,我点击“保存”按钮,输入数据为product_name = car 和code = 123,之后警报出现,我只需点击一次“ok”。 Then later, I click 'save' button with input data of product_name = car and code = 124 after that the alert show up and I have to click 'ok' Two time.然后,我单击“保存”按钮,输入数据为product_name = car 和code = 124,之后警报出现,我必须单击“确定”两次。

The same go for 'Delete' button as well.同样的 go 也用于“删除”按钮。

What should I do?我应该怎么办?

My code on actual page on react app.我在反应应用程序的实际页面上的代码。

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import 'bootstrap/dist/css/bootstrap.min.css'
import ButtonBar from '../components/buttonBar'
import InputGroup from 'react-bootstrap/InputGroup'
import FormControl from 'react-bootstrap/FormControl'
import BrandList from '../components/brandList'
import ModelList from '../components/modelList'
import Button from 'react-bootstrap/Button'
import ButtonGroup from 'react-bootstrap/ButtonGroup'
import {connectToDatabase} from "../util/mongodb"
import {useForm} from "react-hook-form";

export default function AddItem({item}) {

const {register, handleSubmit, watch, errors} = useForm();
const onSubmit = (data) => {
  console.log(data)


  document.getElementById('buttons').addEventListener('click', function(evt) {
     var target = evt.target;
     if (target.id === 'add_item') {
        fetch('/api/item', {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, *same-origin, omit
            headers: {
            'Content-Type': 'application/json'// 'Content-Type': 'application/x-www-form-urlencoded',
        },
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            body: JSON.stringify(data) // body data type must match "Content-Type" header
      })
      .then(response => response.json())
      .then(data => {
        console.log(data);
        alert("Response from server " + data.message)
      });
  } else if (target.id === 'del_item') {
    fetch('/api/item', {
        method: 'DELETE', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify(data) // body data type must match "Content-Type" header
      })
      .then(response => response.json())
      .then(data => {
        console.log(data);
        alert("Response from server " + data.message)
      });
  }
}, false);} return (
<form onSubmit = {handleSubmit(onSubmit)}>
<Head >
   <title> Add / Edit </title> <link rel = "icon" href = "/favicon.ico" / >
</Head>
<main className = {styles.main}>
<p className = {styles.title}>Add / Edit `</p>


Product Name: < input type = "text" name = "product_name" ref = {register({required: true})}/><br / >

Product Code: < input type = "text" name = "code"ref = {register}/><br / >

</main>

   <div id = "buttons" >
      <Button variant = "danger" type = "submit" value = "DELETE" id = "del_item"> Delete </Button{' '}
      <Button type = "submit" value = "POST" id = "add_item" > Save < /Button>{' '}
      <Button variant = "dark" > Back < /Button>{' '}
   </div> <
/form>)}

export async function getServerSideProps() { const {db} = await connectToDatabase();
const item = await db
   .collection("item")
   .find({})
   .sort({})
   .limit(20)
   .toArray();

return {
   props: {
      item: JSON.parse(JSON.stringify(item)),
   },
};}

My APi:我的 APi:

import { connectToDatabase } from "../../util/mongodb";

export default async (req, res) => {
   console.log("item API method " + req.method)

   if (req.method === 'GET') {
      const { db } = await connectToDatabase();
      const item = await db
         .collection("item")
         .find({})
         .sort({})
         .limit(20)
        .toArray();
      res.json(balance);
   } else if (req.method === 'POST') {
      console.log("item REQ", req.body)
      let data = req.body;

      let { product_name, code, brand, model, avi_model, purchase_price, amount, limit_amount, barcode_id, date } = data;

      const { db } = await connectToDatabase();
      let doc = await db
         .collection('item')
         .updateOne(
            {
              product_name: product_name,
              code: code,
              brand: brand,
              model: model,
              avi_model: avi_model,
              purchase_price: purchase_price,
              amount: amount,
              limit_amount: limit_amount,
              barcode_id: barcode_id,
              date: date
            },
            { $set: data },
            { upsert: true }
         ) // if update non-existing record, insert instead.

      res.json({ message: 'OK' });
   } else if (req.method === 'DELETE') {
      let data = req.body
      let { product_name } = data;
      const { db } = await connectToDatabase();
      let doc = await db 
         .collection('item')
         .deleteOne({ product_name: product_name})
      res.json({delete: true, message: 'Delete data', data: {}})
   }}

You're getting multiple alerts triggered because you're adding an event listener every time a submit action happens (when clicking on either "Save" or "Delete").您会触发多个警报,因为每次提交操作发生时(单击“保存”或“删除”时)都会添加事件侦听器。

To fix this, with minimal code changes, you could simply update the onSubmit function by removing the addEventListener and checking for the submitter ID instead.要解决此问题,只需更改最少的代码,您只需通过删除addEventListener并检查提交者 ID 来更新onSubmit function。

const onSubmit = (data, e) => {
    console.log(data);

    const submitterId = e.nativeEvent.submitter.id;
    if (submitterId === 'add_item') {
        // Your `Add Item` logic here
    } else if (submitterId === 'del_item') {
        // Your `Delete Item` logic here
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用多个 React 钩子 useEffect 从 API 中获取数据,当第二次获取时使用第一个钩子中的数据 - Fetch data from API with multiple React hook useEffect when second fetch use data from first hook 反应钩子 useEffect 以在按钮单击时获取数据(打字稿) - react hook useEffect to fetch data on button click (typescript) React/nextjs 在按钮单击时获取数据,但按钮位于不同的组件中 - React/nextjs fetch data on a button click, but the button is in a different component 在按钮单击时反应获取数据 - react fetch data on button click 反应-单击按钮即可从外部API函数获取 - React - Fetch from external API function on button click React useEffect hook 中的 Fetch API 没有响应 - No response from Fetch API in React useEffect hook 单击表单的搜索按钮时从API获取数据,并在React JS的另一页上显示数据 - Fetch data from API when form's search button clicked and show data on another page in React JS 如何在单击按钮时从 API 获取数据 - Javascript? - How to fetch data from API on button click - Javascript? 如何在 React 中的单击按钮上使用 fetch API 设置状态 - how to setState with fetch API on click button in React 从API检索数据时React hook有什么问题 - What is the problem in React hook when retrieve data from API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM