({ children })
| 47 | }; |
| 48 | |
| 49 | const SocketProvider = ({ children }) => { |
| 50 | const [state, dispatch] = useReducer(socketReducer, initialState); |
| 51 | |
| 52 | const { socket, wsTimeoutDuration } = state; |
| 53 | |
| 54 | useEffect(() => { |
| 55 | // run once on first render |
| 56 | (async () => { |
| 57 | try { |
| 58 | const response = await fetch("config.json"); |
| 59 | const data = await response.json(); |
| 60 | if (Object.prototype.hasOwnProperty.call(data, "wsUrl")) { |
| 61 | dispatch({ |
| 62 | type: "initSocket", |
| 63 | url: data.wsUrl, |
| 64 | }); |
| 65 | } else { |
| 66 | console.error("config.json is invalid"); |
| 67 | } |
| 68 | } catch (e) { |
| 69 | console.error(e.message); |
| 70 | } |
| 71 | })(); |
| 72 | }, []); |
| 73 | |
| 74 | useEffect(() => { |
| 75 | if (!socket) return; |
| 76 | |
| 77 | socket.onopen = () => { |
| 78 | dispatch({ type: "resetTimeout" }); |
| 79 | dispatch({ type: "resetTimeoutDuration" }); |
| 80 | console.log("Connected to websocket"); |
| 81 | }; |
| 82 | |
| 83 | socket.onclose = (e) => { |
| 84 | const { reason } = e; |
| 85 | console.log( |
| 86 | `Socket is closed. Reconnect will be attempted in ${Math.min( |
| 87 | wsTimeoutDuration / 1000 |
| 88 | )} second. ${reason}` |
| 89 | ); |
| 90 | |
| 91 | const timeout = setTimeout(() => { |
| 92 | //check if websocket instance is closed, if so renew connection |
| 93 | if (!socket || socket.readyState === WebSocket.CLOSED) { |
| 94 | dispatch({ type: "renewSocket" }); |
| 95 | } |
| 96 | }, wsTimeoutDuration); |
| 97 | |
| 98 | dispatch({ |
| 99 | type: "updateTimeout", |
| 100 | timeout, |
| 101 | }); |
| 102 | }; |
| 103 | |
| 104 | // err argument does not have any useful information about the error |
| 105 | socket.onerror = () => { |
| 106 | console.error(`Socket encountered error. Closing socket.`); |
nothing calls this directly
no outgoing calls
no test coverage detected