Reputation: 491
I have two states:
const [firstState, setFirstState] = useState(6.5)
const [secondState, setSecondState] = useState(3.5)
I wish to combine these two states into an object, like this:
const [myObject, setMyObject] = useState({
first: {firstState},
second: {secondState}
});
//NOTE: This does not compile when i try to create state-object with state values.
I then send the object to a child-component as a prop which is later used for display.
<ChildComponent objectToChild={myObject}/>
What's the best pratice to combine states into an object?
Upvotes: 1
Views: 68
Reputation: 5508
You can simply create an object as an argument in useState method, so It would be like this:
const [user, setUser] = useState({});
and call setUser
method like this:
setUser(prevState => {
return {...prevState, [user.firstState]: 6.5}
}
Read more about useState hook here: https://pl.reactjs.org/docs/hooks-reference.html#usestate
Upvotes: 0
Reputation: 566
Their are different option
1. Using the useState Hook
const [myObject, setMyObject] = useState({
first: firstState,
second: secondState
});
modify state
setMyObject({...myObject, firstState })
2. Using the useReducer
useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
const initialState = {
first: 'name',
second: 'surname'
};
const reducer = (state, action) => {
switch (action) {
case 'first': return { ...state, first: state.first };;
case 'second': return { ...state, second: state.second };;
default: throw new Error('Unexpected action');
}
};
use it like
const [state, dispatch] = useReducer(reducer, initialState);
Upvotes: 1