Can if statements be used within usestates?

Viewed 58

I have a useState as follows:

const [Total, setTotal] = useState(props.location.state.data.price)  

I would like to have it so if props.location.state.data.price is defined, it renders, but if undefined, then it returns 0.

I've tried nullish coalescing operators but it is not working. Any help is appreciated. Thanks

2 Answers

Either like this:

const [Total, setTotal] = useState(props.location?.state?.data?.price ?? 0)  

or like this:

const [Total, setTotal] = useState(
  props.location &&
  props.location.state &&
  props.location.state.data &&
  props.location.state.data.price || 0
)  

You probably would want to also update total if props.location.state.data.price should change at some point, right? So I'd do that with an effect:

const [total, setTotal] = useState(0)  

useEffect(() => {
   if (!props.location?.state?.data?.price) {
       setTotal(0);
       return;
   }
   setTotal(props.location.state.data.price);
}, [props.location.state.data.price])

Related