Home > Back-end >  how to shrink multiple state function into one in react.js
how to shrink multiple state function into one in react.js

Time:09-14

import React from "react";
import { AiOutlineArrowDown, AiOutlineArrowUp } from "react-icons/ai";
import { useState } from "react";

const Vote = () => {
  const [num, setnum] = useState(0);

  const numdown = () => {
    num != 0 ? setnum(num - 1) : setnum(num);
  };
  const numup = () => {
    num < 9 ? setnum(num   1) : setnum(num);
  };
  const [num2, setnum2] = useState(0);

  const numdown2 = () => {
    num2 != 0 ? setnum2(num2 - 1) : setnum(num2);
  };
  const numup2 = () => {
    num2 < 9 ? setnum2(num2   1) : setnum2(num);
  };
  var value1 = (
    <>
      <AiOutlineArrowDown onClick={numdown} />
      {num}
      <AiOutlineArrowUp onClick={numup} />
    </>
  );
  var value2 = (
    <>
      <AiOutlineArrowDown onClick={numdown2} />
      {num2}
      <AiOutlineArrowUp onClick={numup2} />
    </>
  );

  return (
    <>
      {value1}
      {value2}
    </>
  );
};

export default Vote;

(in the upper code i have written a code template to form a poll area with two voted values having increament and decreament function.The vote values lies between 0 to 9 as explained in two ternary operator functions) !!!how to shrink this code into one state function and inreament and decrement function with same working??????

CodePudding user response:

It's a good question. Basically, you can handle all duplicated logic using custom hooks.

You can see a live example here: Edit brave-forest-6l4f53

CodePudding user response:

I think you are looking something like this:

App.js

import { useState } from "react";

export default function App() {
  let [data, setData] = useState(0);
  const handleData = (type) => () => {
    setData((prvState) => {
      return type === "up" ?   prvState : --prvState;
    });
  };

  return (
    <div>
      <button onClick={handleData("up")} style={{ marginRight: "5px" }}>
        Up
      </button>
      {data}
      <button onClick={handleData("down")} style={{ marginLeft: "5px" }}>
        Down
      </button>
    </div>
  );
}

If you want the same thing multiple times then you can create a component and modify this code accordingly.

Run the code in the sandbox I am providing for playing around.

  • Related