1

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?

6
  • Why? why you have to do that ? why you don't use two variable in one useState and pass this for ChildComponent Commented Oct 1, 2019 at 13:47
  • 1
    Maybe useReducer might be more appropriate for you Commented Oct 1, 2019 at 13:47
  • 2
    You can create this as an object so it would be useState({ firstState: 6.5, secondState: 3.5 }); and later use this as an simply js object Commented Oct 1, 2019 at 13:52
  • Can i stil update the state though? @Freestyle09 Commented Oct 1, 2019 at 13:56
  • @ArastoSahbaei Yes you can still update the state do it like setObject({...myObject, firstState: 20}) this will change only the firstState part of the object Commented Oct 1, 2019 at 14:07

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.