Home > Back-end >  React ternary operation for useState()
React ternary operation for useState()

Time:07-05

I am new to React. I have the following setup to initialise my component's state based on a condition, using a ternary operation.

const defaultValue = ['bar']
const myComponent = ({data}) => {

 const foo = (data) => {
   // ...
 }
 const [values, setValues] = Object.keys(data).length > 0 ? useState(foo(data)): useState(defaultValue);

 return (<Comp state={values} />);

}
export default myComponent

The idea is that the initial state will be dependent on the variable 'data' if it is not empty, otherwise it will be assigned a default value. It is now assumed that 'data' is not empty.

I have it that foo() is being called when I expect it, and the argument, data, is also as I expect. If I log the array that foo returns, it is exactly as I want. Unfortunately, when I log 'state' from inside the Comp component, it is the defaultValue.

If I add a console.log("renders") towards the top of myComponent, I get that printout twice, which I suspect is part of the problem?

If this setup is unconventional please let me know and I'll refactor, but if there is a simple work around that somebody is aware of, please let me know!

CodePudding user response:

It's difficult to give better advice without seeing a bit more code. However, you can use a enter image description here

Ref:

https://beta.reactjs.org/learn/state-a-components-memory#meet-your-first-hook

  • Related