REACT-SELECT - Set Value from WEB-API and Update on selection.

          REACT-SELECT - Set Value from WEB-API and Update on selection.

import Select from "react-select";






let [CountryList, SetCountryList] = useState([]);

// This will store the current selected value : same is required to assign the value to react-select on runtime selection. If same is not done selected value will not get updated 

// Properties [id and countryName] name and case has to match with the data field which is 
// comming from JSON. [GetCountryList]

let [CountrySelected ,setCountrySelected] = useState({id:0, countryName:""});

let [StateMasterData, SetStateMasterData] = useState({
    id: 0,
    stateName: "",
    countryID: 0,
    countryName:"",
  });

 //Fetch API
  useEffect(() => {
    GetCountryList();
    if (location.state.ID !== 0) {
      GetData(location.state.ID);
    }
  }, [location.state.ID]);


// Get Data from web -API and fille the Country list object 
  async function GetCountryList() {
    let response = await fetch(
      "http://Localhost:2030/api/Country/GetAllCountry",
      {
        method: "GET",
        mode: "cors", //change this
        headers: { "Content-Type": "application/json" },
      }
    );
    let result = await response.json();
    if (result !== null) {
      SetCountryList(result);
    }    
  }

// Get Data to fill the select [react-select] control
 async function GetData(ID) {
    let response = await fetch(
      "http://Localhost:2030/api/State/GetStateByID/?ID=" + ID,
      {
        method: "GET",
        mode: "cors",
        headers: { "Content-Type": "application/json" },
      }
    );
    let result = await response.json();
    if (result !== null) {
      SetStateMasterData({
        id: result.id,
        stateName: result.stateName,
        countryID: result.countryID,
        countryName: result.countryName,
      });     
      // This is required to set value to country select/Combobox 
     // (Data which is return from DB/WEBAPI JSON)
      setCountrySelected({id:result.countryID, countryName:result.countryName})
    }    
  }

// TO EVENT TO HANDLE SELECT/COMBOBOX Change. 
//This will store the selected value into state and 
//At same time will update the base Object of module which will further 
//used in saving and validation

const handleCboChange = (selectedOption) => {
    let crtyId = 0;
    setCountrySelected(selectedOption)
    if (selectedOption !== null) {
      crtyId = selectedOption.id;
    }

// Update the control value to state.
 const handleInputChange = (e) => {
    const { name, value } = e.target;
    SetStateMasterData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
  };

return{
<div>
          <Stack direction="row" spacing={2}>
            <TextField
              required
              type="text"
              id="State-Name"
              name="stateName"
              label="State Name"
              size="small"
              value={StateMasterData.stateName}
              sx={{ width: 330 }}              
              onChange={handleInputChange}
              helperText={ErrorStateMasterData.stateName}
              inputProps={{
                maxLength: 40,
              }}
            />           
            <TextField
              disabled
              id="id"
              label="ID"
              size="small"
              value={StateMasterData.id}
              sx={{ width: 50 }}              
            />
          </Stack>
        </div>

<div style={{ marginTop: "10px" }}>
          <Stack direction="row" spacing={2}  >
            // CONTAINER TO MANAGE WIDTH OF SELECT
            <div style={{ width: "330px" }}>  
             
              <Select
                name="Countries"
                isClearable="true"
                isSearchable="true"
                options={CountryList}     // DATASOURCE            

                // TO HANDLE CHANGE EVENT. WHICH CAN UPDATE THE SELECTED VALUE 
               // TO STATE. WHICH IS USED TO SET THE VALUE TO SELECT/COMBOBOX   
                onChange={handleCboChange}  

                getOptionLabel={(option) => option.countryName}

               // It should be unique value in the options. E.g. ID
                getOptionValue={(option) => option.id} 

               // VALUE FROM STATE (WHEN IN EDIT MODE AND 
               //  SAME IS USED WHEN USE SELECT THE VALUE)
                value={CountrySelected} 
             />
            </div>
            />
          </Stack>
        </div>
}

Comments

Popular posts from this blog

Shared / Static Class in vb.net/C#

Xamarin Forms : PopUp Page with RG.Plugins.Popup

Text was truncated or one or more characters had no match in the target code page.". (SQL Server Import and Export Wizard)