Skip to content

Instantly share code, notes, and snippets.

View kylephughes's full-sized avatar

Kyle Hughes kylephughes

  • Gemini
  • Westwood, NJ
View GitHub Profile
import { notificationObservable } from 'services/notificationService'
const Notification = () => {
const [notification, setNotification] = useState('')
useEffect(() => {
// called when component first mounts
const subscription = notificationObservable.subscribe((value) => {
// re-render with new value
setNotification(value)
})
return () => {
import { publishNotification } from './notificationService'
const FormComponent = () => {
const handleNotifcation = () => {
publishNotification('Success!')
}
return (
// <button onClick={handleNotification} />
)
}
import { Subject } from 'rxjs'
const notificationSubject = new Subject()
// Subject is also an Observable
const notificationObservable = notificationSubject.asObservable()
const publishNotification = (value) => {
// multicasts a value onto the stream
notificationSubject.next(value)
}
// <Notification/>
import { useSelector } from 'react-redux'
export const Notification = (props) => {
const notification = useSelector((state) => state.notification)
}
// <FormComponent/>
import { useDispatch } from 'react-redux'
export const FormComponent = (props) => {
// <App/>
export const NotificationContext = React.createContext({...})
return (
<NotificationContext.Provider value={{ notification, setNotification }}>
// any child component can consume these values directly
</NotificationContext.Provider>
)
export const App = () => {
const [notification, setNotification] = useState('') // where should this state live?
return (
<Hierarchy1>
<Component1>
<Notification/> // renders a notification
</Component1>
</Hierarchy1>
<Hierarchy2>
<Component2>