Search code examples
javascriptreactjsundefined

Uncaught TypeError: Cannot read properties of null (reading 'isReceivedCall')


I am trying to make a video chat app. I want the answer button to be activated when a call comes in. But I am getting this error:

enter image description here

My Notification.jsx file looks like this:

import React, { useContext } from 'react';
import { Button } from '@mui/material';
import { SocketContext } from '../SocketContext';

const Notification = () => {
    const { answerCall, call, callAccepted, isReceivedCall } = useContext(SocketContext);

    return (
        <>
            {call.isReceivedCall && !callAccepted && (
                <div style={{ display: 'flex', justifyContent: 'space-around' }}>
                    <h1>{call.name} is calling:</h1>
                    <Button variant="contained" color="primary" onClick={answerCall}>
                        Answer
                    </Button>
                </div>
            )}
            Notification
        </>
    )
}

export default Notification

This is how I defined isReceivedCall in SocketContext:

socket.on('calluser', ({ from, name: callerName, signal }) => {
            setCall({ isReceivedCall: true, from, name: callerName, signal })
        });
    }, []);


Solution

  • If you console.log in the component, you will probably find that it renders once, then gets context and renders again. The issue is that the first render, SocketContext is null.

    So you need to just handle that appropriately, perhaps like:

    if(!call) return <></<>
    
    return (
            <>
                {call.isReceivedCall && !callAccepted && (
                    <div style={{ display: 'flex', justifyContent: 'space-around' }}>
                        <h1>{call.name} is calling:</h1>
                        <Button variant="contained" color="primary" onClick={answerCall}>
                            Answer
                        </Button>
                    </div>
                )}
                Notification
            </>
        )
    

    But also a bit confused, looks like you pull call from context, as well as isCallReceived but isCallReceived is a property of call. It seems like you dont want to pull isCallReceived off of context in the first place.

    In other words, you destructure isCallReceived here: const { answerCall, call, callAccepted, isReceivedCall } = useContext(SocketContext);

    but that property exists on call. Unless you just have two different isReceivedCall values, which in that case, ignore this confusion.