0

In my React app, I have two pages where I'm collecting information from users (that don't need to register or login). On the first page, I collect personal information and save it in a MySQL table that has an auto-incrementing primary key id. On the second page, I ask additional questions and want to link the answers to the corresponding personal information using a foreign key since I need to retrive them later in a page where I'm gonna show my user some results. How can I retrieve the ID from the first table and use it as the foreign key (infoId) in the second table when saving the answers? I'm using Axios for API calls and MySQL for the database

First page:

pages/Info.jsx

import React, { useState } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import { useNavigate } from "react-router-dom";

const Information = () => {
  const [answers, setAnswers] = useState({});

  const handleChange = (e) => {
    setAnswers((prev) => ({
      ...prev,
      [e.target.name]:
        e.target.value,
    }));
  };


  const saveAnswers = async () => {

    try {
      await axios.post("http://localhost:8800/server/information", answers)
      navigate("/map")
    }catch(err){
      console.log(err)

    }
  };


  return (
    <div className="w-full py-[2rem] px-4 bg-white">
      <div className="max-w-[800px] mt-24 w-full mx-auto text-center flex flex-col justify-center">
        <h1 className="md:text-7xl text-[#009999] sm:text-6xl text-4xl font-bold md:py-6">
          Text
        </h1>
      </div>
      <div className="max-w-[800px] w-full mx-auto text-center flex flex-col">
        <form>
    [My form code]
        </form>

          <button
            className="bg-black text-[#e3e3e3] w-[200px] rounded-md font-medium my-6 mx-auto px-6 py-3"
            onClick={saveAnswers}
          >
            Continua
          </button>
  
      </div>
    </div>
  );
};

export default Information 

controllers/info.js

export const addInfo = (req,res)=>{
    const q = 'INSERT INTO survey_Info (, `age`, `adress`, `phone`) VALUES (?)'

    const values = [
        req.body.age,
        req.body.adress,
        req.body.phone,
    ]

    db.query(q, [values], (err, data) =>{
        if (err) return res.status(500).json(err);
        return res.status(200).json("Info has been sent succesfully");
    })
}

Second page code:

import React, { useState } from "react";
import Questions from "./question.json";
import { Link } from "react-router-dom";

const question = () => {
  const [answers, setAnswers] = useState({});

  console.log(answers);

  const handleChange = (e) => {
    setAnswers((prev) => ({
      ...prev,
      [e.target.name]:
        e.target.value,
    }));
  };

  const saveAnswers = async () => {

    try {
      await axios.post("http://localhost:8800/server/question", answers)
      navigate("/map")
    }catch(err){
      console.log(err)

    }
  };

  

  return (
    <div className="w-full py-[2rem] px-4 bg-white">
      <div className="max-w-[800px] w-full mx-auto text-center flex flex-col">
        <form>

    [My form code]
        </form>

        {/* full button on mobile */}

        <Link to="/results">
          <button
            className="bg-black text-[#e3e3e3]  w-[200px] rounded-md font-medium my-6 mx-auto px-6 py-3"
            onClick={calculateSum}
          >
            Continua
          </button>
        </Link>
      </div>
    </div>
  );
};

export default question;

and my controllers/question.js

import { db } from "../connect.js"


export const addAnswer = (req,res)=>{
    const q = 'INSERT INTO question (`infoId`, `question_1`, `question_2`,`question_3`,`question_4`) VALUES (?)'

    const values = [
        "InfoId",
        req.body.question_1,
        req.body.question_2,
        req.body.question_3,
        req.body.question_4,

    ]

    db.query(q, [values], (err, data) =>{
        if (err) return res.status(500).json(err);
        return res.status(200).json("question has been sent succesfully");
    })
}
Pisa Ponente
  • 123
  • 1
  • 9

1 Answers1

0

If using typescript MySQL2, you can retrieve the id of new row insertions using .insertId:

// info.js
...
db.query(q, [values], (err, data) => {
    if (err) return res.status(500).json(err);
        const infoId: number = data.insertId; // This is the id of the new row
        ...
    })
}

Edit: see See Retrieve last inserted id with Mysql.

ee-4-me
  • 267
  • 1
  • 8