๋ฆฌ์กํธ ๋ค์ดํฐ๋ธ์ ์น์์ผ ์ ์ฉํ๊ธฐ
๋ฆฌ์กํธ ๋ค์ดํฐ๋ธ์์ ์น์์ผ ํต์ ์ ์ฌ์ฉํ๊ธฐ ์ํด์ WebSocket์ ์ฌ์ฉํ๋ผ๊ณ ๊ถ์ฅํ๋ค.
ํ์ด์ค๋ถ ๊ณต์๋ฌธ์ - https://reactnative.dev/docs/network#websocket-support
ํ์ฌ ํจ์ํ ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ๊ณ ์๋๋ฐ, ์ฒ์์ ์ปดํฌ๋ํธ๊ฐ ์์ฑ๋ ๋ ์ต์ด 1ํ๋ง ์น์์ผ์ ์ฑ๋์ ์์ฑํด์ผ ํ๋ค. ๋ฐ๋ผ์, useEffect hook์ ์ฌ์ฉํด์ ์ต์ด 1ํ ์น์์ผ์ ์ ์ํ๋ค.
useEffect(() => {
let ws = new WebSocket(`ws://127.0.0.1:8000/ws/room/`)
ws.onopen = () => {
// connection opened
console.log('connected')
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
return () => {
ws.close();
};
}, [])
์น์์ผ ์ธ์คํด์ค์ scope ๋ฌธ์
ํ์ง๋ง ์ด๋ ๊ฒ useEffect hook ์์์ ์ ์๊ฐ ๋๊ธฐ ๋๋ฌธ์ ๋ค๋ฅธ ํจ์์์ ์น์์ผ ์ธ์คํด์ค๋ฅผ ์ฌ์ฉํ ์ ์๊ฒ ๋๋ค. ์ด๋ฅผ ํด๊ฒฐํ๋ ๋ฐฉ์์ผ๋ก useRef hook์ ์ฌ์ฉํ๋ผ๊ณ ํ๋ค.
ํด๊ฒฐ๋ฐฉ์ - https://stackoverflow.com/questions/60152922/proper-way-of-using-react-hooks-websockets
const ws = useRef(null);
useEffect(() => {
ws.current = new WebSocket(`ws://127.0.0.1:8000/ws/room/`)
console.log(ws.current)
ws.current.onopen = () => {
// connection opened
console.log('connected')
// send a message
};
ws.current.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.current.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.current.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
return () => {
ws.current.close();
};
}, [])
ref๋ ๋จ์ํ DOM๋ฟ๋ง ์๋๋ผ, ๊ฐ์ฒด๋ค์ ์ ์ฅํ๋ ๊ธฐ๋ฅ์ผ๋ก๋ ์ฌ์ฉํ ์ ์๋ค๊ณ ํ๋ค.
The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. more
'๐ก ๊ณตํ์ > ์ฝ๋ฉ ์ํ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์๊ณ ์์ ์นด์นด์ค ๋ก๊ทธ์ธ api ์ฌ์ฉํ๊ธฐ (0) | 2021.11.10 |
---|---|
[web]Firebase์ ๊ฐ๋จ ์นํธ์คํ ํ๊ธฐ (0) | 2021.09.28 |
[web]Godaddy ์ปค์คํ ๋๋ฉ์ธ Firebase์ ์ฐ๊ฒฐํ๊ธฐ (0) | 2021.09.28 |
[react]Context Api ์ฌ์ฉํ์ฌ ๋ก๊ทธ์ธ ๋ฐ์ดํฐ ๊ด๋ฆฌํ๊ธฐ (0) | 2021.09.28 |
[django]Session Authentication๊ณผ Cookie (0) | 2021.09.28 |