Home > Software design >  How to combine useState hook with switch cases in react
How to combine useState hook with switch cases in react

Time:12-20

Here is component with the array of items, counters val and spiceValue and rendering block with adding some quantity of spices for example. Every spice has own price, adding or removing by click on plus or minus. How to implement this logic according to best practices of react?

export const SpiceBlock = ({ isCalculated }) => {
  const [spiceQuantity, setSpiceQuantity] = useState(0);
  var val = 0;
  var spiceValue = 0;

Calling useEffect with passed val as argument in any part of this code could not to read val

useEffect((val) => {
  setSpiceQuantity();
}, []);

  const spicesCount = (event) => {
    const direction = event.target.dataset.direction;
    const dataSpice = event.target.dataset.spice;
    switch (dataSpice) {
      case "guarana":spiceValue = 21;break;
      case "zhen":spiceValue = 11;break;
      case "cinnamon":spiceValue = 33;break;
      case "tapioka":spiceValue = 41;break;
      default:return false;
    }

    if (direction === "plus") {
      val  = spiceValue;
    } else if (val - spiceValue > 0) {
      val -= spiceValue;
    }
  };
 
  const spicesArr = [
    { name: "Guarana", data: "guarana" },{ name: "Zhenshen", data: "zhen" },
    { name: "Cinnamon", data: "cinnamon" },{ name: "Tapioka", data: "tapioka" },
  ];

  return (
    <div className={`spiceItems ${isCalculated ? "calculated" : ""}`}>
      {isCalculated && spicesArr
        ? spicesArr.map((spice, index) => (
            <div className="counter" key={`spice${index}`}>
              <button
                className="counter__btn"
                data-direction="minus"
                data-spice={spice.data}
                onClick={spicesCount}
              >
                -
              </button>
              <label htmlFor="spice" type="text">
                {spice.name}
                <input
                  type="text"
                  name="spice"
                  value={val}
                  disabled
                  className="counter__value"
                />
                {spiceQuantity}
              </label>
              <button
                className="counter__btn"
                data-direction="plus"
                data-spice={spice.data}
                onClick={spicesCount}
              >
                 
              </button>
            </div>
          ))
        : null}
    </div>
  );
};

CodePudding user response:

Any variable that is not a state will disappear after rerender, it's better to store variables in the state

const [value, setValue] = useState()

const getValue = type => {
  switch (dataSpice) {
    case "guarana": return 21;
    case "zhen": return 11;
    case "cinnamon": return 33;
    case "tapioka": return 41;
  }
}

const spicesCount = (event) => {
  const direction = event.target.dataset.direction;
  const dataSpice = event.target.dataset.spice;
  
  const val = getValue(dataSpice);

  if (direction === "plus") {
    setValue(value => value   spiceValue)
  } else if (val - spiceValue > 0) {
    setValue(value => value - spiceValue)
  }
};
<input
  type="text"
  name="spice"
  value={value}
  disabled
  className="counter__value"
/>

CodePudding user response:

Set val as a state and add it as a dependency to your useEffect. So that every time you set the value of val the setSpiceQuantity function will be triggered


const [val, setVal] = useState(0);

useEffect(() => {
  setSpiceQuantity();
}, [val]);

if (direction === "plus") {
      setVal(val  = spiceValue)
    } else if (val - spiceValue > 0) {
      setVal(val -= spiceValue)
    }
  • Related