Skip to content

Commit

Permalink
refactor: use callback prop for installation status messaging
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardo committed Oct 9, 2023
1 parent 0cc7188 commit 67ad85b
Showing 1 changed file with 11 additions and 28 deletions.
39 changes: 11 additions & 28 deletions src/PluginWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useCacheableSection, CacheableSection } from '@dhis2/app-runtime'
import { CenteredContent, CircularLoader, Layer } from '@dhis2/ui'
import postRobot from '@krakenjs/post-robot'
import PropTypes from 'prop-types'
import React, { useEffect, useState } from 'react'
import React, { useEffect } from 'react'
import { Visualization } from './components/Visualization/Visualization.js'
import { getPWAInstallationStatus } from './modules/getPWAInstallationStatus.js'

Expand Down Expand Up @@ -68,36 +68,15 @@ CacheableSectionWrapper.propTypes = {
isParentCached: PropTypes.bool,
}

const sendInstallationStatus = (installationStatus) => {
postRobot.send(window.parent, 'installationStatus', { installationStatus })
}

const PluginWrapper = () => {
const [propsFromParent, setPropsFromParent] = useState()

const receivePropsFromParent = (event) => setPropsFromParent(event.data)
const PluginWrapper = (props) => {
const { onInstallationStatusChange, ...propsFromParent } = props

useEffect(() => {
postRobot
.send(window.parent, 'getProps')
.then(receivePropsFromParent)
.catch((err) => console.error(err))

// Get & send PWA installation status now, and also prepare to send
// future updates (installing/ready)
// Get & send PWA installation status now
getPWAInstallationStatus({
onStateChange: sendInstallationStatus,
}).then(sendInstallationStatus)

// Allow parent to update props
const listener = postRobot.on(
'newProps',
{ window: window.parent /* Todo: check domain */ },
receivePropsFromParent
)

return () => listener.cancel()
}, [])
onStateChange: onInstallationStatusChange,
}).then(onInstallationStatusChange)
}, [onInstallationStatusChange])

return propsFromParent ? (
<div
Expand All @@ -118,4 +97,8 @@ const PluginWrapper = () => {
) : null
}

PluginWrapper.propTypes = {
onInstallationStatusChange: PropTypes.func,
}

export default PluginWrapper

0 comments on commit 67ad85b

Please sign in to comment.