0

i want to send message while typing text by using websocket.

but have websocket reference error while typing text.

i think ShareTextComponent onInputEvent function parameter is not exeucte in another location.

so websocket property can't reference in this field

but i don't know how can i fix it.

and i didn't use any state management library such as redux and mobx.

just pure reactjs

[error]

enter image description here

[code]

const ShareTextComponentView = (props) => {

const [isShareMode, setShareMode] = useState(false)
const [syncText, setSyncText] = useState("")
const [isOpen, setOpen] = useState(false)
const [name, setName] = useState("")

let ws = null;
const connect = () => {
    ws = new WebSocket(ADDRESS + `/${name}`)

    //액세스코드들을 전부 보냄
    ws.onopen = () => {
        ws.send(JSON.stringify({command: "CONNECT", accessCode: generateAccessCode()}))
        console.log(`${ADDRESS}에 접속 되었습니다.`)
        setOpen(true)
    }

    ws.onclose = () => {
        ws.send(JSON.stringify({command: "CLOSE"}))
        console.log(`${ADDRESS}에 접속 종료 되었습니다.`)
        setOpen(false)
    }

    ws.onmessage = (evt) => {
        if (isShareMode) {
            return
        }

        const message = JSON.parse(evt.data)
        console.log({message: message})
        setSyncText(message.data)
    }
    ws.onerror = (err) => {
        console.log("접속중에 에러가 발생되었습니다.")
        console.log(err)
    }
}

const close = () => {
    if (ws !== null && ws.readyState !== WebSocket.CLOSED) {
        ws.close()
    }
}

// p2p로 웹소켓으로 연결
useEffect(() => {
    if (isOpen) {
        return
    }

    connect()
    setOpen(true)

    return () => {
        //만약 공유모드를 종료했을때 websocket에 shutdown 메세지를 보냄
        if (isOpen) {
            close()
            console.log(`${ADDRESS}에 접속 종료 되었습니다.`)
        }
        setOpen(false)
    }

}, [isShareMode])

const onTextInput = (text) => {
    const {name, value} = text.target

    if (!isShareMode) {
        return
    }

    console.log("websocket status")
    console.log(ws)
    console.log("input value")
    console.log(value)
    if (ws.readyState === WebSocket.CLOSED) {
        console.log("Connect Close 되었습니다.")
    } else {
        ws.send(JSON.stringify({command: "SEND", message: value}))
    }
}

const generateAccessCode = () => {
    return "hello"
}


const reconnect = () => {
    connect()
    console.log(ws)
}
return (
    <div className="container">
        <h1> Please Enter This Area Section</h1>
        <h1> {isOpen ? "Connect" : "Disconnect"}</h1>
        <div className="name-container">
            <label> Name : </label>
            <input type="text" onChange={(e) => {
                setName(e.target.value)
            }}/>
        </div>
        <button className="reconnect-mode" onClick={reconnect}>Connect</button>
        <button className="is-receiever" onClick={() => setShareMode(!isShareMode)}>공유자 입니까?</button>
        <h1>{isShareMode ? "공유모드" : "수신모드"}</h1>
        <ShareTextComponent accessCode={generateAccessCode()} onInputEvent={onTextInput} syncText={syncText}/>
    </div>
)
}
export default ShareTextComponentView;

[after logging in onTextInput]

enter image description here

1 Answer 1

0

Add a null check to the top of the function ->

const onTextInput = (text) => {
    if (!ws) return;

This will at least help you get past that error and narrow down the rest of the flow.

3
  • but i want to send server while typing text. so i want to ws property is not null in onTextInput method. however while reconnect function is work property while i've check the log but only onTextInput ws proptery is emtpy :(
    – raje ku
    May 14, 2021 at 19:23
  • i don't know why ws property have null after connect function is work property
    – raje ku
    May 14, 2021 at 19:34
  • Ah, I think it's because you are re-defining ws with every component render. Either pull this out of the component or make the variable a ref with the useRef hook. It will not change on re-render and once connect is called it will be set up for use in the other functions. May 14, 2021 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.