0

I want to get my id with setImmediate and copy it with CopyToClipboard. I guess I'm pulling the value as blank on the page because the setImmediate function has been removed. What can I use instead of this function and get my id value?

This is the error I get in the console. I tried to print the id in options.jsx and it comes up blank as you can see.

enter image description here

This is my page view. When I click the blue button, an id needs to be copied and I want to paste that id into the input and start a search. However, I cannot perform the operation because the id is empty.

enter image description here

SocketContext.js file (take the id)

import React, { createContext, useState, useRef, useEffect } from 'react';
import { io } from 'socket.io-client';
import Peer from 'simple-peer';

const SocketContext = createContext();
const socket = io('http://localhost:5000');

const ContextProvider = ({ children }) => {
    const [stream, setStream] = useState(null);
    const [me, setMe] = useState('');
    const [call, setCall] = useState(null);
    const [callAccepted, setCallAccepted] = useState(false);
    const [callEnded, setCallEnded] = useState(false);
    const [name, setName] = useState('');

    const myVideo = useRef();
    const userVideo = useRef();
    const connectionRef = useRef();

    useEffect(() => {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then((currentStream) => {
                setStream(currentStream);
                if (myVideo.current) {
                    myVideo.current.srcObject = currentStream;
                };
            });
            
            
            // HERE 
        socket.on('me', (id) => setImmediate(id));
        
        
        socket.on('calluser', ({ from, name: callerName, signal }) => {
            setCall({ isReceivedCall: true, from, name: callerName, signal })
        });
    }, []);

    const answerCall = () => {
        setCallAccepted(true);

        const peer = new Peer({ initiator: false, trickle: false, stream });

        peer.on('signal', (data) => {
            socket.emit('answercall', { signal: data, to: call.from });
        });

        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream;
        });
        peer.signal(call.signal);
        connectionRef.current = peer;
    }

    const callUser = (id) => {
        const peer = new Peer({ initiator: true, trickle: false, stream });
        peer.on('signal', (data) => {
            socket.emit('calluser', { userToCall: id, signalData: data, from: me, name });
        });
        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream;
        });
        socket.on('callaccepted', (signal) => {
            setCallAccepted(true);
            peer.signal(signal);
        });
        connectionRef.current = peer;
    }

    const leaveCall = () => {
        setCallEnded(true);
        connectionRef.current.destroy();
        window.location.reload();
    }

    return (
        <SocketContext.Provider value={{
            call, callAccepted, myVideo, userVideo, stream, name, setName, callEnded, me, callUser, leaveCall,
            answerCall
        }}>
            {children}
        </SocketContext.Provider>
    );
}

export { ContextProvider, SocketContext };

Options.jsx file (copy to id)

import React, { useContext, useState } from "react";
import { Button, TextField, Grid, Typography, Container, Paper } from "@mui/material";
import { createTheme } from '@mui/material/styles';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { Assignment, Phone, PhoneDisabled } from '@mui/icons-material';
import { SocketContext } from "../SocketContext";

const theme = createTheme();

const rootStyles = {
    display: 'flex',
    flexDirection: 'column',
};
const gridContainerStyles = {
    width: '100%',
    [theme.breakpoints.down('xs')]: {
        flexDirection: 'column',
    },
};
const containerStyles = {
    width: '800px',
    margin: '10px 0',
    padding: 0,
    [theme.breakpoints.down('xs')]: {
        width: '80%',
    },
};
const marginStyles = {
    marginTop: 2,
};
const paddingStyles = {
    padding: 2,
};
const paperStyles = {
    padding: '1px 2px',
    border: '2px solid black',
};

const Options = ({ children }) => {
    const { me, callAccepted, name, setName, callEnded, leaveCall, callUser } = useContext(SocketContext);
    const [idToCall, setIdToCall] = useState('');

    return (
        <Container sx={containerStyles}>
            <Paper elevation={10} sx={paperStyles}>
                <form sx={rootStyles} noValidate autoComplete="off00">
                    <Grid container sx={gridContainerStyles}>
                        <Grid item xs={12} md={6} sx={paddingStyles}>
                            <Typography gutterBottom variant="h6">Account Info</Typography>
                            <TextField label="Name" value={name} onChange={(e) => setName(e.target.value)}
                                fullWidth />
                                
                                
                            {/* COPY TO ID PART*/}
                            {console.log(me)}
                            <CopyToClipboard text={me} sx={marginStyles} >
                                <Button variant="contained" color="primary" fullWidth
                                    startIcon={<Assignment fontSize="large" />}>
                                    Copy Your ID
                                </Button>
                            </CopyToClipboard>
                            
                            
                        </Grid>
                        <Grid item xs={12} md={6} sx={paddingStyles}>
                            <Typography gutterBottom variant="h6">Make a Call</Typography>
                            <TextField label="ID to Call" value={idToCall}
                                onChange={(e) => setIdToCall(e.target.value)}
                                fullWidth />
                            {callAccepted && !callEnded ? (
                                <Button variant="contained" color="danger" fullWidth
                                    startIcon={<PhoneDisabled fontSize="large" />} onClick={leaveCall}
                                    sx={marginStyles}>Hang Up</Button>
                            ) : (
                                <Button variant="contained" color="success" fullWidth
                                    startIcon={<Phone fontSize="large" />} onClick={() => callUser(idToCall)}
                                    sx={marginStyles}>Call</Button>
                            )}
                        </Grid>
                    </Grid>
                </form>
                {children}
            </Paper>
        </Container>
    )
}

export default Options
idil
  • 69
  • 6
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate#browser_compatibility – derpirscher Mar 25 '23 at 11:28
  • I've looked here and I know it's no longer used, I used postMessage instead but I still keep getting the value blank – idil Mar 25 '23 at 11:33
  • What are you actually trying to achieve with `setImmediate(id)`? The first parameter of `setImmediate` should be a function, but `id` is some kind of value, isn't it? – derpirscher Mar 25 '23 at 11:39
  • Here is me in index.js io.on('connection', (socket) =>{ socket.emit('me', socket.id); }); I am trying to send id value from socketcontext to options – idil Mar 25 '23 at 11:42
  • Well, yes, but what's the purpose of `setImmediate` in that case, that doesn't "send" or "set" anything. It just calls the function that was passed as first parameter. But in your case that `id` is not a function but a value. So even if `setImmediate` was still available, that wouldn't work ... – derpirscher Mar 25 '23 at 13:04
  • That's how he did it in the tutorial I watched, and it works in that. So how can I send this id to my options file? – idil Mar 25 '23 at 13:19

1 Answers1

1

It looks like you're calling setImmediate but that is not defined (which makes sense because setImmediate is a function of window, not a standalone function).

Using some context clues, ie based on how your copy works, do you mean to use setMe there? I'm guessing your code editor auto-corrected setMe to setImmediate. The comment above assumes you're actually trying to use setImmediate but it doesn't make sense that you'd be using that here, and setMe is unused AND your copy function is using me, so I'm almost certain it's a typo.

e.g: instead of: socket.on('me', (id) => setImmediate(id));

socket.on('me', (id) => setMe(id));

TomLV
  • 365
  • 1
  • 11
  • That's how he did it in the tutorial I watched, and it works in that... This works too, thank you so much, you saved me! – idil Mar 25 '23 at 14:19
  • No problem! Something I've learned over the years with tutorials, is that a lot of them are made in a way where the creator first writes the code off recording, then starts recording and just types out the code again while reading it from a second monitor, almost like a news anchor reading from a teleprompter, so they'll make mistakes and not catch them because they're not thinking about what the code is actually doing anymore. That may have been what happened here. – TomLV Mar 25 '23 at 14:25
  • Probably that's the problem, you're right. – idil Mar 25 '23 at 14:33