Search code examples
javascriptreactjsselectdefault

React : why I have to click twice on the same option to set in select box


import ProductCard from "./ProductCard";
import "../Styles/Products.css";
import "../Styles/Filter.css";
import { v4 as uuidv4 } from "uuid";

const Products = (props) => {
  const skins = props.skins;
  // const [filteredSkins, setFilteredSkins] = useState();
  const [gameFilter, setGameFilter] = useState("DEFAULT");

  const [qualityFilter, setqualityFilter] = useState("DEFAULT");
  let skinsObj = {};

  let qualityObj = {};

  for (let i = 0; i < skins.length; i++) {
    skinsObj[skins[i].gameName] = i;

    qualityObj[skins[i].quality] = i;
  }

  const setGame = (e) => {
    setGameFilter(e.target.value);
    console.log(gameFilter, qualityFilter);
  };

  const setquality = (e) => {
    setqualityFilter(e.target.value);
    console.log(gameFilter, qualityFilter);
  };
  console.log(gameFilter, qualityFilter);
  return (
    <React.Fragment>
      <div className="filter_option">
        <div className="filter_by_game Filter-Box">
          <label htmlFor="games">Game : </label>
          <select name="games" id="games" onChange={(e) => setGame(e)}>
            <option value="DEFAULT">All</option>
            {Object.keys(skinsObj).map((game) => {
              return (
                <option value={game} key={uuidv4()}>
                  {game}
                </option>
                //
              );
            })}
          </select>
        </div>

        <div className="filter_by_quality Filter-Box">
          <label htmlFor="quality">Quality : </label>
          <select name="quality" id="quality" onChange={(e) => setquality(e)}>
            <option value="all">All</option>
            {Object.keys(qualityObj).map((quality) => {
              return (
                <option value={quality} key={uuidv4()}>
                  {quality}
                </option>
                //
              );
            })}
          </select>
        </div>
      </div>
      <div className="product-wrapper">
        {skins &&
          skins.map((skin) => {
            return (
              <ProductCard
                key={uuidv4()}
                className="product-list"
                name={skin.name}
                icon={skin.gameName}
                price={skin.price}
                quality={skin.quality}
                picture={skin.picture}
              />
            );
          })}
      </div>
    </React.Fragment>
  );
};

export default Products;

I need to click on any option from the list twice in a row to be applied in the box but the state change when I log it, also the second select affected when I change the other one both get reset to default try some solution but nothing help don't know if it is problem with the way of importing data or what


Solution

  • You currently don't set the value prop on <select>.