Stefan Vucic
Stefan Vucic

Reputation: 35

Is it possible to handle Multiple useState hooks with one simple function?

This question may sound silly, but it would help me a lot in my React projects and it would significantly reduce amount of code.

I have some code like following:

const [user, setUser] = useState({
      name: "",
      password: ""
      });

const [name, setName] = useState("");
const [password, setPassword] = useState("");

const handleInput = (e) => {  

I would like to do this

      let inputHandler =`set${(e.target.name.slice(0,1)).toUpperCase()}${e.target.name.slice(1)}`;
      inputHandler(e.event.value);

like I am doing this

      setUser({...user,
           [e.target.name]:e.target.value
      });

};

<input onChange={handleInput} name="name"></input>
<input onChange={handleInput} name="password"></input>
           

The point is to update different states "genericly", like I am doing with one state properties. The code above is really simplified, in my project there are 10+ states to handle and I achieved that with 200 lines of code :D

Upvotes: 1

Views: 213

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53974

Just pass a callback to your "generic function":

const handleInput = (e, set) => {
  set(`${e.target.name.slice(0, 1).toUpperCase()}${e.target.name.slice(1)}`);
};

// Usage
onClick={e => handleInput(e, setUser)}

// Or as curried function
const genInputHandler = set => e => {
  set(`${e.target.name.slice(0, 1).toUpperCase()}${e.target.name.slice(1)}`);
};

// Usage
onClick={genInputHandler(setUser)}

Upvotes: 1

Related Questions