Created
March 19, 2024 19:12
-
-
Save maiconrs95/8d3f84570d53368b23e12cd94742f823 to your computer and use it in GitHub Desktop.
A custom hook to help post message state management
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react'; | |
export function isDevelopment() { | |
return process.env.NODE_ENV === 'development'; | |
} | |
const domain = `${isDevelopment() ? 'http' : 'https'}://${window.location.host}`; | |
const addPrefix = (key: string) => `some-prefix-${key}`; | |
export const sendMessage = <Data>(key: string, state: Data) => | |
window.parent.postMessage({ key: addPrefix(key), state }, domain); | |
export const useMessageState = <Data>(key: string): Data | undefined => { | |
const [state, setState] = useState<Data | undefined>(undefined); | |
useEffect(() => { | |
const handleMessage = (event: MessageEvent) => { | |
if (event.data.key === addPrefix(key)) { | |
setState(event.data.state); | |
} | |
}; | |
window.addEventListener('message', handleMessage); | |
return () => { | |
window.removeEventListener('message', handleMessage); | |
}; | |
}, [key]); | |
return state; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment