Home > Mobile >  Auto selecting dependent select field options in React
Auto selecting dependent select field options in React

Time:07-07

I am using React v18.

I tried to populate react-select options from api, it didn't work as expected. Anyway, its fine with normal select as of now.

I have a row of select boxes as shown below. Dependent select fields When I select the ID , it shall auto select the category and product name.

On the other hand, selecting the category should shortlist the product options(it is working). Upon selecting the product name from the list, the ID should be selected automatically.

My question is, how shall we auto select the option value for a select field?

Sharing my code so far.

--------------------------------
         dselect.js 
--------------------------------
import Select from "react-select"
import {Row, Col, Container, Form} from "react-bootstrap"
import React, { useState } from 'react';
import { useEffect } from "react";
const baseurl = "http://localhost:5000/api";
const Dselect=()=>{
         
     const [pdtCode, setPdtCode] = useState([]);
     const [catList, setCatList] = useState([]);
     const [pdtList, setPdtlist] = useState([]);

/* **here all the options are fetched for the ID and category** */

     useEffect(()=>{
          const fetchCat = async(e) => {
               const res = await fetch(`${baseurl}/cat`);
               const cList = await res.json();
               console.log(cList)
               setCatList(cList)
               }         

          const fetchPdtName = async(e) => {
               const res = await fetch(`${baseurl}/pdtlist`);
               const pList = await res.json();
               console.log(pList)
               setPdtlist(pList)
               }

               fetchCat();
               fetchPdtName();
     },[])

/* Here, fetch the product name and category upon selecting a pdt code */
     const getPdtDetails = async(e) => {
          const pdtID = e.target.value;
          console.log(pdtID)
          const res = await fetch(`${baseurl}/details`,{
               method: "POST",
               headers: { "Content-Type": "application/json" },
               body: JSON.stringify({data:pdtID}),  
               });
          const detList = await res.json();
               // console.log(detList)

      /* STORED VALUES . BUT DONT KNOW HOW TO USE THESE VALUES TO AUTO SELECT THE OPTIONS*/

          const pdt_name=detList.pdt_name;
          const category=detList.category;
          } 
     
       /* GETTING PRODUCT LIST ON SELECTING THE CATEGORY. THIS PART IS WORKING WELL */

          const updateList = async(e) =>{
               const catVal = e.target.value;
               const res = await fetch(`${baseurl}/pdtList`,{
                         method: "POST",
                         headers: { "Content-Type": "application/json" },
                         body: JSON.stringify({data:catVal}),  
                         });
               const pdtList = await res.json();
               console.log(pdtList)
               setPdtlist(pdtList)
          }

        /* FETCH PRODUCT CODE BASED ON THE CATEGORY AND PRODUCT NAME SELECTED */
         
        const getPdtcode = async(e) =>{

       /* ? * QUESTION : HOW CAN I GET THE CATEGORY VALUE HERE? IT IS NECESSARY TO 
                     FETCH THE APT PRODUCT ID FROM THE DB */

               const pdtVal = e.target.value;
               const res = await fetch(`${baseurl}/pdtCode`,{
                         method: "POST",
                         headers: { "Content-Type": "application/json" },
                         body: JSON.stringify({data:pdtVal}),  
                         });
               const code = await res.json();
               console.log(code)
               setPdtCode(code);
          }

return(
     <div>
          <Container className="m-5">
               <Row>
                    <Col lg={4} md={4} xs={6}>
                         <label>ID</label>


{/* <Select options={pdtList} placeholder="Select product" /> */} /* Failed with react-select*/

                         <select name="product_id" onChange={(e)=>getPdtDetails(e)} >
                         <option value="">-</option>
                              {pdtList.map((item) =>(
                                   <option key={item.pdt_id} value={item.pdt_id}> {item.pdt_id} </option>
                              ))}
                         </select>
                    </Col>

                    <Col lg={4} md={4} xs={6}> <label>Category</label>                             
                         <select name="category" onChange={updateList}  >
                              <option value="">-</option>
                              {catList.map((item) =>(
                                   <option key={item.cat_id} value={item.category}>{item.category}</option>
                              ))}
                         </select>                              
                    </Col>
                    <Col lg={4} md={4} xs={6}> <label>Product </label>
                        <select name="product" onChange={getPdtcode} >
                         <option value="">-</option>
                              {pdtList.map((item) =>(
                                   <option key={item.pdt_id} value={item.pdt_id}> {item.pdt_name} </option>
                              ))}
                         </select>                     
                    </Col>
               </Row>
          </Container>
     </div>
)    
}
  
export default Dselect

Any piece of advise or help is appreciated. Thanks in advance.

Let me share the list data as well.

Category list

Category list

Products list

Products list

CodePudding user response:

import React, { useState } from "react";
import Select from "react-select";

const options = [
  { value: "chocolate", label: "Chocolate" },
  { value: "strawberry", label: "Strawberry" },
  { value: "vanilla", label: "Vanilla" }
];

export default function App() {
  const [selectedOption, setSelectedOption] = useState({
    value: "chocolate",
    label: "Chocolate"
  });

  return (
    <div className="App">
      <Select
        value={selectedOption}
        onChange={setSelectedOption}
        options={options}
      />
    </div>
  );
}

CodePudding user response:

Thanks for the answers @sedhal. I have almost fixed the issues and am able to auto-select values using react-select. Posting my final code here.

import Select from "react-select";
import { Row, Col, Button, Container, Form } from "react-bootstrap";
import React, { useState } from "react";
import { useEffect } from "react";

const baseurl = "localhost:5000/api";
const Dselect = (props) => {

  const [pdtCodeOptions, setPdtCodeOptions] = useState([]);
  const [catListOptions, setCatListOptions] = useState([]);
  const [pdtListOptions, setPdtListOptions] = useState([]);

  const [selectedCat, setSelectedCategory] = useState();
  const [selectedPcode, setSelectedPCode] = useState();
  const [selectedPName, setSelectedPName] = useState();

  useEffect(() => {
    const fetchCat = async (e) => {
      const res = await fetch(`${baseurl}/cat`);
      const cList = await res.json();

      let catOpt = [];
      for (let i = 0; i < cList.length; i  ) {
        catOpt.push({ label: cList[i].category, value: cList[i].category });
      }
      setCatListOptions(catOpt);
    };

    const fetchPdtCode = async (e) => {
      const res = await fetch(`${baseurl}/pdtlist`);
      const pList = await res.json();
      const pdtList = [];
      for (let i = 0; i < pList.length; i  ) {
        pdtList.push({ label: pList[i].pdt_id, value: pList[i].pdt_id });
      }
      setPdtCodeOptions(pdtList);
    };

    fetchCat();
    fetchPdtCode();
  }, []);

  const getPdtDetails = async (e) => {
    const pdtID = e.value;

    const res = await fetch(`${baseurl}/details`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ data: pdtID }),
    });
    const detList = await res.json();

    const pdt_name = detList[0].pdt_name;
    const category = detList[0].category;

    setSelectedCategory({ label: category, value: category });
    setSelectedPName({ label: pdt_name, value: pdt_name });
  };

  const updateList = async (e) => {
    const catVal = e.value;
    console.log(e);

    const res = await fetch(`${baseurl}/pdtList`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ data: catVal }),
    });
    const pdtList = await res.json();

    const catPdtList = [];
    for (let i = 0; i < pdtList.length; i  ) {
      catPdtList.push({
        label: pdtList[i].pdt_name,
        value: pdtList[i].pdt_name,
      });
    }
    setPdtListOptions(catPdtList);
  };

  const getPdtcode = async (e, index) => {
    **/* ? * here, i want to get the category value also */**
    const pdtVal = e.value;
    const res = await fetch(`${baseurl}/pdtCode`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ data: pdtVal }),
    });
    const code = await res.json();
    console.log(code);
    setSelectedPCode(code);
  };

  return (
    <Row className="mt-3">
      <Col lg={3} md={3} xs={3}>
        <label>ID</label>
        <Select
          options={pdtCodeOptions}
          placeholder="Select product"
          value={selectedPcode}
          onChange={(e) => {
            console.log({ selectedPcode });
            setSelectedPCode(selectedPcode);
            getPdtDetails(e);
          }}
        />
      </Col>

      <Col lg={3} md={3} xs={3}>
        <label>Category</label>
        <Select
          options={catListOptions}
          placeholder="Category"
          value={selectedCat}
          onChange={(e) => {
            setSelectedCategory(selectedCat);
            updateList(e);
          }}
        />
      </Col>
      <Col lg={3} md={3} xs={3}>
        <label>Product </label>
        <Select
          options={pdtListOptions}
          onChange={(e) => {
            setSelectedPName(selectedPName);
            getPdtcode(e);
          }}
          value={selectedPName}
          placeholder="Select product"
        />      
      </Col>
    </Row>
  );
};

export default Dselect;
  • Related