jon-perrett
jon-perrett

Reputation: 94

React useState with the output of a ternary expression

I am creating an app which replaces lots of untracked excel sheets with a database which is using a React/FastAPI stack.

I have a form component which works for uploading new items to the database, and I am looking to reuse that same component for editing items in the database. As such I have a flag isEdit which is passed from the parent component as a prop to determine if it is a new entry or an edited entry. I am using isEdit in a ternary expression to determine whether to set state using a sensible default object, or an object which has values described by the item we are looking to edit. In short the code looks like this:

const blankItem = ***sensible object***
const editItem = ***object constructed from the data to edit***

(this above constructs what I would expect)

const initValue = isEdit ? editItem : blankItem
const [item, setItem] = useState(initValue)

No matter which way I refactor this code, and whether or not isEdit is true or false the initial value of item is always equal to blankItem.

Upvotes: 1

Views: 301

Answers (2)

vijayakm
vijayakm

Reputation: 102

Have you try this :

const [state, setState] = useState(() => {
  const initialState = isEdit ? editItem : blankItem
  return initialState;
});

The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded. If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render

From : https://reactjs.org/docs/hooks-reference.html#lazy-initial-state

Upvotes: 2

Andrew Freitas
Andrew Freitas

Reputation: 1

Why not pass the item itself as a prop instead of the flag?

Alternatively maybe a useEffect might help?

useEffect(() => {
  if (isEdit) {
    setItem(editItem)
  else {
    setItem(blankItem)
  }
}, [isEdit])

Upvotes: 0

Related Questions