skip to Main Content

I have two select in an Component and i want to change the table_id select options when type select change but i quite don’t understand how to get database again when select option changed.

Here is my code:

import { faBackward, faFloppyDisk } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Link, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";

import menuservice from "../../../services/MenuService";

function MenuCreate() {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const [link, setLink] = useState("");
  const [table_id, setTable_id] = useState(0);
  const [type, setType] = useState("");
  const [status, setStatus] = useState(1);
  async function postStore(event) {
    event.preventDefault();
    const image = document.querySelector("#image");
    var menu = new FormData();
    menu.append("name", name);
    menu.append("link", link);
    menu.append("table_id", table_id);
    menu.append("type", type);
    menu.append("status", status);
    menu.append("image", image.files[0]);

    try {
      await menuservice.create(menu).then(function (res) {
        alert(res.data.message);
        navigate("../../admin/menu", { replace: true });
      });
    } catch (error) {
      console.error(error.response.data);
    }
  }
  const [menus, setMenus] = useState([]);
  useEffect(function () {
    (async function () {
      await menuservice.getAll().then(function (result) {
        setMenus(result.data);
      });
    })();
  }, []);
  return (
    <section className="mainList">
      <div className="wrapper">
        <div className="card1">
          <form method="post" onSubmit={postStore}>
            <div className="card-header">
              <strong className="title1">THÊM MENU</strong>
              <div className="button">
                <Link to="/admin/menu" className="backward">
                  <FontAwesomeIcon icon={faBackward} />
                  Go back
                </Link>
                <button type="submit" className="save">
                  <FontAwesomeIcon icon={faFloppyDisk} />
                  Save
                </button>
              </div>
            </div>
            <div className="form-container grid -bottom-3  ">
              <div className="grid__item large--three-quarters">
                <fieldset className="input-container">
                  <label htmlFor="name">Tên menu</label>
                  <input
                    name="name"
                    type="text"
                    className="input"
                    id="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Nhập tên menu..."
                  />
                </fieldset>
                <fieldset className="input-container">
                  <label htmlFor="link">Đường dẫn menu</label>
                  <input
                    name="link"
                    type="text"
                    className="input"
                    id="name"
                    value={link}
                    onChange={(e) => setLink(e.target.value)}
                    placeholder="Nhập đường dẫn..."
                  />
                </fieldset>
              </div>
              <div className="grid__item large--one-quarter">
                <fieldset className="input-container">
                  <label htmlFor="type">Chọn loại menu</label>
                  <select
                    name="type"
                    className="input"
                    value={type}
                    onChange={(e) => setType(e.target.value)}
                  >
                    <option disabled>--Chọn loại menu--</option>
                    <option value="mainmenu">Menu chính</option>
                    <option value="footermenu">Menu footer</option>
                  </select>
                </fieldset>
                <fieldset className="input-container">
                  <label htmlFor="table_id">Chọn menu cha</label>
                  <select
                    name="table_id"
                    className="input"
                    value={table_id}
                    onChange={(e) => setTable_id(e.target.value)}
                  >
                    <option disabled>--Chọn menu cha--</option>
                    <option value="0">Không có cha</option>
                    {menus.map((menu, index) => {
                      return (
                        <option key={index} value={menu.id}>
                          {menu.name}
                        </option>
                      );
                    })}
                  </select>
                </fieldset>
                <fieldset className="input-container">
                  <label htmlFor="status">Tình trạng xuất bản</label>
                  <select
                    name="status"
                    className="input"
                    value={status}
                    onChange={(e) => setStatus(e.target.value)}
                  >
                    <option disabled>--Chọn tình trạng xuất bản--</option>
                    <option value="1">Xuất bản</option>
                    <option value="2">Không xuất bản</option>
                  </select>
                </fieldset>
              </div>
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

export default MenuCreate;

So i when i change the type select, it will call a function to get database base on option chosen then map() that array to type select.

2

Answers


  1. just make a state variable of type boolean and set initial value be false
    like-

    const [variablename,setvariablename) = useState(false);
    

    now in make a function to fetch values of second options based on first option and bind all the statements of the function inside the if condition saying like this

    function fetchSecondoptions(){
    if(variablename){ statements }
    }
    

    now use a use effet hook and in dependancy array place that variable so when it changes the function vill be called. and data will be fetched.

    like

    useEffect(() => {
     fetchSecondoptions();
    }, [variablename]);
    
    Login or Signup to reply.
  2. Like when you change state of table_id by using setTable_id then you have to trigger an useEffect on table_id change just like this

    useEffect(()=>{
    
     if(table_id !==0){
       setStatus("1") // the value you want to set
       setType("mainmenu")
     }
    
    },[table_id]) // you have to add the changing variable in the dependency array
    

    In this useEffect when table_id is changes then it automatically changes the value of other select

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search