Home > database >  Confused about changing state in a certain way
Confused about changing state in a certain way

Time:08-13

I have a page in NextJS for editing an sql row and sending it back. I have fetched all the rows from the table and then have set the state to be the single row which matches the query parameter in the useRouter hook. Now, after I have edited the data in the row, what is a good way to POST it back to the backend? Below is my React code:

import { React, useEffect, useState } from "react";
import { useRouter } from "next/dist/client/router";
const axios = require("axios");

export default function Edit() {
  const [data, setData] = useState([]);
  const router = useRouter();

  const onSubmitHandler = (e) => {
    e.preventDefault();
    axios.post("/api/cards", data);
  };

  useEffect(() => {
    const fetchData = async () => {
      await axios
        .get("/api/cards")
        .then((res) => {
          if (res.data) {
            res.data.map((element) => {
              if (element.ID == router.query.card) {
                setData(element);
                return;
              }
              return;
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    if (router.isReady) {
      fetchData();
    }
  }, [router.isReady, router.query.card]);

  return (
    <form onSubmit={onSubmitHandler}>
      <label htmlFor="front">Front</label>
      <input
        defaultValue={data.Front}
        id="front"
        onChange={(e) => setData({ ...data, Front: e.target.value })}
      ></input>
      <label htmlFor="back">Back</label>
      <input
        defaultValue={data.Back}
        id="back"
        onChange={(e) => setData({ ...data, Back: e.target.value })}
      ></input>
      <button type="submit">Add Word</button>
    </form>
  );
}

Below is my backend code

if (req.method === "POST") {
    const { front, back, type } = req.body.data;
    const id = uuidv4();
    db.query(
      `INSERT INTO deck VALUES('${front}', '${back}', '${type}', '${id}')`,
      (err, rows, fields) => {
        if (!err) {
          res.json(rows);
        } else {
          console.log(err);
        }
      }
    );
  }

CodePudding user response:

Its good to post the edited data after submiting the form..

const onSubmitHandler =  async (e) => {
    e.preventDefault();
    try {
     await axios.post("/api/cards", data); 
     // react-toast or something like that to indicate the ui the form is updated 
     // then the control flow of the application  
     } catch (error){
        console.error(error)
     }
   
  };

CodePudding user response:

One thing I notice over here is you're using POST for the update. Try HTTP PUT instead of POST.

And regarding your answer: You can send modified data in your API call like you're already maintaining the state of the updated data. Then you can just send that row to the API call and handled that in your backend code.

const onSubmitHandler = (e) => {
    e.preventDefault();
    axios.put("/api/cards/:id", data); // modify the API URL and append dynamic ID of the record. 
  };
  • Related