Created
December 23, 2017 06:46
-
-
Save alexander-heimbuch/c6e8f00b0ffb34de66ea606a4cf2a0ec to your computer and use it in GitHub Desktop.
Redux Webworker Middleware
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 { get } from 'lodash' | |
export const connectToWorker = Worker => { | |
const worker = new Worker() | |
let registered = false | |
return (store, action) => { | |
const state = store.getState() | |
if (!registered) { | |
worker.addEventListener('message', ({ data }) => store.dispatch(data)); | |
registered = true | |
} | |
worker.postMessage({ action, state }) | |
} | |
} | |
export const connectToStore = worker => cb => { | |
worker.addEventListener('message', ({ data }) => { | |
cb({ | |
dispatch: worker.postMessage, | |
getState: () => get(data, 'state', {}) | |
}, | |
get(data, 'action', {}) | |
) | |
}) | |
} |
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 { connectToWorker } from 'utils/worker' | |
import Worker from './demo.worker.js' | |
export default connectToWorker(Worker) |
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 { connectToStore } from 'utils/worker' | |
const subscribe = connectToStore(self) | |
subscribe((store, action) => { | |
console.log(action, store.getState()) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment