1

I am new to React and have a question about useState. I have this code:

const [value, setValue] = useState(props.selectedNote.content);

The problem is that selectedNote is sometimes null and sometimes not. If it is null then this throws an error. How can I work around this?

6 Answers6

3

Optional chaining is fantastic:

const [value, setValue] = useState(props.selectedNote?.content);

If you want a default value in the case that selectedNote (or content) is null/undefined then you can use nullish coalescing

const [value, setValue] = useState(props.selectedNote?.content ?? 'default');
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31
  • This works!! One question: for some reason `value` doesn't change when `props.selectedNote?.content` changes. Do you know why this could be? –  Oct 12 '20 at 15:22
  • 1
    The `(props.selectedNote?.content)` is the initial value of the state. After that, the state is set. So, you'd need a `useEffect(()=>{setValue(props.selectedNote?.content)},[props.selectedNote?.content])` to update the state every time the selectedNote changes. Otherwise you might not want to `useState` for it and just pull the content into a variable and use that. – Zachary Haber Oct 12 '20 at 15:29
0

You can try

const [value, setValue] = useState(props.selectedNote?props.selectedNote.content:null)

Deepak Gupta
  • 614
  • 1
  • 7
  • 14
0

You can manage it with a ternary operator as suggested by @deepakgupta. Another possibility, useful when you have a lot of props to check, is that of assign defaultProps to the component. This will avoid all a bunch of check inside component body and let the code more clean.

function myComponent(props) {
    const [value, setValue] = useState(props.selectedNote.content);
}

myComponent.defaultProps = {
    selectedNote : {
        content : null
    }
    ...
    anotherProp : 'my default value'
}
Nja
  • 439
  • 6
  • 17
0

It's depends from your application business logic.

  1. Conditional Rendering
const Comp = (props) => {
   const [value, setValue] = useState(props.selectedNote?.content);

   return value ? < some your staff > : <SkeletonForNoValue />;
}
  1. You may define default value
const Comp = (props) => {
   const [value, setValue] = useState(props.selectedNote?.content || defaultNote);

  1. Push to another route
const Comp = (props) => {
   const [value, setValue] = useState(props.selectedNote?.content);

   useEffect(
     () => {
        history.push({
          pathname: '/path/to/go'
        }
     },
     [props.selectedNote]
   )
  1. Any other logic implementation...
Gleb Shaltaev
  • 234
  • 1
  • 6
0

Try this:-

const [value, setValue] = useState(props.selectedNote && props.selectedNote.content);

maya_nk99
  • 502
  • 3
  • 5
0

Try this : const [value, setValue] = useState(props.selectedNote?.content || defaultNote);

Sabesan
  • 654
  • 1
  • 10
  • 17