Home > Software design >  Is there a way to dynamically choose which state I want to update in react?
Is there a way to dynamically choose which state I want to update in react?

Time:07-19

For example if I have a bunch of useState hooks such as:

const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [location, setLocation] = useState('')

and a function that takes a string value such as:

const handleClick = string => console.log(string)  // Name

Is there any way of dynamically choosing which state I update by passing the string value to the function call? Something along the lines of:

const handleClick = (string) => {
    console.log(string)  // Name
    set${string}('John Doe')
}

CodePudding user response:

A single object is usually used for this.

const [state, setState] = useState({
  name: '',
  age: 0,
  location: ''
})

const handleClick = (key, value) => setState({...state, [key]: value});

You could also do something like this:

const [name, setName] = useState('')
const [age, setAge] = useState(0)
const [location, setLocation] = useState('')

const map = {
  name: setName,
  age: setAge,
  location: setLocation
}

const handleClick = (string) => {
    map[string]('John Doe')
}

CodePudding user response:

You can achieve this behaviour by grouping your states into one

const [state, setState] = useState({
  name: '',
  age: 0,
  location: '',
});

const handleClick = (key, value) => {
  setState((prev) => ({...prev, key: value}))    
}
  • Related