UNPKG

react-window-communication-hook

Version:
93 lines (77 loc) 3.02 kB
'use strict'; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _require = require('react'), useState = _require.useState, useEffect = _require.useEffect, useRef = _require.useRef; var initialState = { lastMessage: undefined, messages: [] }; var supportsBroadcastAPI = typeof window !== 'undefined' && 'BroadcastChannel' in window; function useBrowserContextCommunication(channelName) { if (channelName === undefined) { throw Error('You need to pass a channel name e.g. useBrowserContextCommunication("GreatChannel")'); } var _useState = useState(initialState), _useState2 = _slicedToArray(_useState, 2), state = _useState2[0], setMessages = _useState2[1]; var channel = useRef(); if (supportsBroadcastAPI) { channel.current = new BroadcastChannel(channelName); } function postMessage(message) { if (message) { var msg = JSON.stringify({ message: message, time: Date.now() }); if (supportsBroadcastAPI && channel && channel.current) { channel.current.postMessage(msg); } else { window.localStorage.setItem(channelName, msg); } } } function updateState(data) { setMessages(function (prevState) { return { lastMessage: data.message, messages: prevState.messages.concat(data.message) }; }); } function updateFromLocalStorage(e) { try { var data = JSON.parse(e.newValue); if (data !== null && data !== undefined) { updateState(data); } } catch (error) { console.info('React Window Communication: Failed to parse json from localstorage'); } } useEffect(function () { if (supportsBroadcastAPI && channel && channel.current) { if (channel && channel.current) { channel.current.onmessage = function (e) { return updateState(JSON.parse(e.data)); }; } } else { window.addEventListener('storage', updateFromLocalStorage); } return function cleanup() { if (channel && channel.current) { channel.current.close(); channel.current = null; } else { window.localStorage.removeItem(channelName); window.removeEventListener('storage', updateFromLocalStorage); } }; }, [channelName]); return [state, postMessage]; } module.exports = useBrowserContextCommunication;