I'm getting the following error: Uncaught TypeError: Cannot read properties of null (reading 'id'). but when i change my initialState (object ) then it works fine
type AnchorElAction = {
id: string;
domTarget: React.ReactNode;
} | null;
const [anchorEl, setAnchorEl] = useState<AnchorElAction | null>(null);
return (
{events?.map((event, index) => {
return (
<Styled.Event key={`${event.id}:${event.name}`} onClick={handleOpenPopover(event.id)}>
{renderShifts(event)}
{anchorEl.id === event.id && (
<ShiftPopover
start={event.start}
end={event.end}
name={event.name}
id={event.id}
onClose={handleCloseModal}
anchorEl={anchorEl.domTarget}
open={Boolean(anchorEl.domTarget)}
/>
)}
</Styled.Event>
);
})}
)
CodePudding user response:
cuz when you do
const [anchorEl, setAnchorEl] = useState<AnchorElAction | null>(null);
anchorEl === null so you can't do anchorEl.id
when you do
const [anchorEl, setAnchorEl] = useState<AnchorElAction>({});
you can access property id in anchorEl so anchorEl === {} and anchorEl.id === null
To fix that, remove null or check when use anchorEl.id like
anchorEl?.id
// if anchorEl === null => anchorEl?.id === null
//if anchorEl === {} => anchorEl?.id === nulll
//if anchorEl === {id : 'any id'} => anchorEl?.id === 'any id'
CodePudding user response:
You could you the .?
operator.
In your case, event.id
you should be changed to event?.id
. In order to avoid similar issues, I would add the .?
operator every time you access a property of event
or any other variable that could be null
or undefined
.
For more information about it, please refer to the official documentation.