score:5

Accepted answer

yes, this is perfectly correct and valid.

i personally, like to create a const initialstate to make it a little easier to read.

const example = (props) => {
  const initialstate = props.bar ? props.bar._id : '';
  const [foo, setfoo] = usestate(initialstate);

  return { foo };
};

as far as accessing _id when bar is undefined. there are a few ways to solve that as well.

one of the new ways to do so is to use the new optional chaining operator ?. and the nullish coalescing operator ?? together.

const initialstate = props.bar?._id ?? '';

if you don't have support for those new operators you could also use the || or operator like so.

const initialstate = (props.bar || {})._id || '';

Related Query

More Query from same tag