while working on code ran into some errors on line 13 when the value is undefined and is reading as 0 please how can I solve this
the error message
homepage.js:13 Uncaught TypeError: Cannot read properties of undefined (reading '0')
const dispatch = useDispatch();
const danceClass = useSelector((state) => state.class);
const { classes } = danceClass;
const [dance, setDance] = useState(
classes[0] ? classes[0].slice(0, 3) : [],
);
CodePudding user response:
If your danceClass object doesn't have a classes property, then classes will be undefined and classes[0] will produce the error you're seeing.
Try using optional chaining instead
const [dance, setDance] = useState(classes?.[0]?.slice(0, 3) ?? []);
The above will also work if classes is an empty array.
CodePudding user response:
Because the classes is undefined. You should check like
classes ? classes[0]?.slice(0,3) : []
