coffeekraken-redux-web-worker v1.0.1
Coffeekraken redux-web-worker
Redux middleware that let you use web worker with ease to handle your expensive (or not) actions
Table of content
Install
npm install coffeekraken-redux-web-worker --save
Get Started
Suppose we have container that trigger a FETCH_TODOS
action like so:
TodoContainer.js
import { registerWorker } from 'coffeekraken-redux-web-worker'
import tasksWorker from './tasks.worker'
import { FETCH_TODOS } from './constants'
class TodoContainer extends React.Component {
componentDidMount() {
registerWorker(tasksWorker)
const { dispatch } = this.props
dispatch({
type: FETCH_TODOS,
payload: 'something'
})
}
}
Note that we have imported and registered the worker before dispatching the action.
Now that we have an action dispatched and our worker registered, let's see the tasks.worker.js
content:
tasks.worker.js
import axios from 'axios'
import { expose } from '../../middlewares/webworker'
import { FETCH_TODOS, TODOS_FETCHED } from './constants'
export default expose({
[FETCH_TODOS]: async ({ dispatch, action, state }) => {
const todos = await axios.get(
'https://my-json-server.typicode.com/coffeekraken/react-boilerplate/todos'
)
dispatch({
type: TODOS_FETCHED,
todos: todos.data
})
}
}, self)
The last step if to apply the middleware as you would do for any other redux middleware. Here's how:
store.js
import { createStore, applyMiddleware } from 'redux'
import webworkerMiddleware from 'coffeekraken-redux-web-worker'
import reducer from './reducers'
// create the store with our middleware
const store = createStore(
reducer,
applyMiddleware(webworkerMiddleware)
)
// render the application
Requirements
In order for this middleware to work, you'll need to install the worker-loader webpack loader.
npm install worker-loader --save-dev
Here's an example of webpack configuration:
webpack.config.js
module.exports = {
//...
module: {
rules: [{
test: /\.worker\.js$/,
use: {
loader: 'worker-loader',
options: {
inline: true,
fallback: false
}
}
}]
}
}
Browsers support
IE / Edge | Firefox | Chrome | Safari |
---|---|---|---|
IE11+ | last 2 versions | last 2 versions | last 2 versions |
As browsers are automatically updated, we will keep as reference the last two versions of each but this component can work on older ones as well.
Contribute
This is an open source project and will ever be! You are more that welcomed to contribute to his development and make it more awesome every day. To do so, you have several possibilities:
Who are Coffeekraken
We try to be some cool guys that build some cool tools to make our (and yours hopefully) every day life better.
More on who we are
License
The code is available under the MIT license. This mean that you can use, modify, or do whatever you want with it. This mean also that it is shipped to you for free, so don't be a hater and if you find some issues, etc... feel free to contribute instead of sharing your frustrations on social networks like an asshole...