spal
spal

Reputation: 338

Can if statements be used within usestates?

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

Upvotes: 2

Views: 79

Answers (2)

Giraphi
Giraphi

Reputation: 1651

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])

Upvotes: 1

Josep
Josep

Reputation: 13071

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
)  

Upvotes: 5

Related Questions