I’m trying to initialize some state for my form component with data from the redux store. If the shippingAddress object is null, I want to set properties of formData object to empty strings. Not sure how to get it to work. Currently I am receiving an error message saying TypeError: Cannot read property 'address' of null
const cart = useSelector((state) => state.cart); const { shippingAddress } = cart; const [formData, setFormData] = useState( { address: shippingAddress.address, city: shippingAddress.city, country: shippingAddress.country, postalCode: shippingAddress.postalCode, } || { address: "", city: "", country: "", postalCode: "", } );
Advertisement
Answer
You could accomplish this with a ternary to first sniff on the presence/absence of shippingAddress
:
const cart = useSelector((state) => state.cart); const { shippingAddress } = cart; const [formData, setFormData] = useState( shippingAddress ? { address: shippingAddress.address, city: shippingAddress.city, country: shippingAddress.country, postalCode: shippingAddress.postalCode, } : { address: "", city: "", country: "", postalCode: "", } );
Alternately, you could use the optional chaining ?.
and nullish coalescing ??
operators to achieve the same affect:
const cart = useSelector((state) => state.cart); const { shippingAddress } = cart; const [formData, setFormData] = useState( { address: shippingAddress?.address ?? '', city: shippingAddress?.city ?? '', country: shippingAddress?.country ?? '', postalCode: shippingAddress?.postalCode ?? '', } );
Please note this second option is a newer JS feature, so check that you have Babel or browser support as is pertinent.