joseluisq / hyperapp-starter

Minimal Hyperapp, Typescript and Parcel starter. :package::rocket::tada:
MIT License
42 stars 6 forks source link

HMR results in duplicate elements #4

Open svicalifornia opened 5 years ago

svicalifornia commented 5 years ago

Steps to reproduce:

  1. Clone repo from current master branch commit
  2. yarn and npm start
  3. Edit src/App.tsx
  4. Cut line 13 (Logo element) and save file
  5. Observe that logo disappears in browser
  6. Paste to restore Logo element back at line 13 and save file
  7. Observe duplicate logo elements in browser
screen shot 2018-11-26 at 5 33 29 am

(Strangely, after saving the file a third time, the duplicate logos disappear, and the app looks right again.)

joseluisq commented 5 years ago

According to this thread the code below works for me:

main.tsx

import { app } from 'hyperapp'
import { actions, state, view } from '@app/app'
import moisturize from 'hyperapp-moisturize'

function makeHotReloader (updateApp) {
  return (fileName, updateAs) => {
    return module.hot.accept(`./${fileName}`, () => {
      import(`./${fileName}?${Date.now()}`)
        .then((imported) => {
          updateApp({
            [updateAs]: imported.default
          })
        })
    })
  }
}

const main = moisturize(app)(state, actions, view, document.body)
const hotReloader = makeHotReloader(main.updateApp)

hotReloader('state.js', 'newState')
hotReloader('actions.js', 'newActions')
hotReloader('view.js', 'newView')

Example taken from okwolf/srvs