With a React Class component i have the following state object as an example:
JavaScript
x
5
1
state = {
2
typeEvent: [],
3
reductionCoefficient: []
4
}
5
when i want to make a function that gets an specific attribute from the state i can simply use
JavaScript
1
4
1
getArray = (name) => {
2
return this.state[name]
3
}
4
Is there something equivalent when i use Hooks? Because i would have to write this
JavaScript
1
12
12
1
const [typeEvent,setTypeEvent] = useState([])
2
const [reductionCoefficient,setCoefRed] = useState([])
3
const getArray = (name) => {
4
if(name=='typeEvent'){
5
return typeEvent
6
}
7
if(name=='reductionCoefficient'){
8
return reductionCoefficient
9
}
10
}
11
12
Advertisement
Answer
You can simply write your both arrays into one state:
JavaScript
1
2
1
const [state, setState] = useState({typeEvent:[], reductionCoefficient:[]});
2
Now just access them by their name:
JavaScript
1
2
1
state.typeEvent
2
or
JavaScript
1
2
1
state.reductionCoefficient
2