Skip to content

Instantly share code, notes, and snippets.

@alyssaq
Created November 30, 2017 11:34
Show Gist options
  • Save alyssaq/8826df9cedbda96da0114c574d668ee8 to your computer and use it in GitHub Desktop.
Save alyssaq/8826df9cedbda96da0114c574d668ee8 to your computer and use it in GitHub Desktop.
webworker react
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import logger from 'redux-logger'
import rootReducer from '../reducers'
import { debounce } from 'lodash'
let prevFilter = ''
function dispatchData(dispatch, data, numRows) {
const allData = data.displayData
prevFilter = data.filterBy
data.displayData = allData.slice(0, numRows)
dispatch(data)
if (allData.length > numRows) {
data.displayData = allData
requestAnimationFrame(() => {
if (prevFilter === data.filterBy) {
//dispatch(data)
dispatchData(dispatch, data, numRows+(numRows*2))
}
})
}
}
const createWorkerMiddleware = (worker) => {
return ({dispatch, getState}) => {
const debounceDispatch = debounce((data) => {
dispatch(data)
}, 100, {leading: true, trailing: true})
const debounceWebWorker = debounce((action) => {
action.payload = getState()[action.webWorkerState]
worker.postMessage(action)
}, 100, {leading: true, trailing: true})
worker.addEventListener('message', (event) => {
dispatchData(dispatch, event.data, 2)
})
return (next) => (action) => {
if (action.useWebWorker) {
debounceWebWorker(action)
// action.payload = getState()[action.webWorkerState]
// worker.postMessage(action)
} else {
return next(action) // Pass action along to the next middleware
}
}
}
}
var blob = new Blob([
'(',
function () {
self.onmessage = ({ data: action }) => {
console.log('worker', action)
self.postMessage({
type: action.type,
payload: {
num: action.payload.num + 1,
},
})
}
}.toString(),
')()'
]);
// Obtain a blob URL reference to our worker 'file'.
// var blobURL = window.URL.createObjectURL(blob);
// URL.revokeObjectURL(blobURL)
const worker = new window.Worker('./worker.js')
export default function configureStore (initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(
// createWorkerMiddleware(worker),
thunk,
logger
)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment