@@ -17,6 +17,7 @@ any messages or errors it sends, as well as the `postMessage` handler.
1717- Provides easy access to the last message ` data ` and last ` error `
1818- Provides ` postMessage ` to send messages to the Web Worker
1919- Provides ` updatedAt ` and ` lastPostAt ` metadata
20+ - Accepts ` parser ` and ` serializer ` for automatic message (de)serialization
2021- Accepts ` onMessage ` and ` onError ` callbacks
2122
2223> This package was modeled after [ ` <Async> ` ] ( https://github.com/ghengeveld/react-async ) which helps you deal with Promises in React.
@@ -80,6 +81,8 @@ const MyComponent = () => (
8081
8182- ` url ` {string} (required) Public url to the Web Worker file (or path relative to the root of your domain)
8283- ` options ` {Object} Options passed to the Worker constructor
84+ - ` parser ` {Function} Transforms incoming messages (not errors)
85+ - ` serializer ` {Function} Transforms ` postMessage ` payload before sending
8386- ` onMessage ` {Function} Callback function invoked when a message is received, passing message data as argument
8487- ` onError ` {Function} Callback function invoked when an error is received, passing error object as argument
8588
@@ -138,6 +141,30 @@ const MyComponent = () => (
138141)
139142```
140143
144+ ### Using ` parser ` and ` serializer ` to automatically parse incoming messages and stringify outgoing messages
145+
146+ ``` js
147+ import WebWorker from " react-webworker"
148+
149+ const MyComponent = () => (
150+ < WebWorker url= " /worker.js" parser= {JSON .parse } serializer= {JSON .stringify }>
151+ {({ data, error, postMessage, updatedAt, lastPostAt }) => (
152+ < div>
153+ {data && (
154+ < div>
155+ < strong> Received some data: < / strong>
156+ < pre> {JSON .stringify (data, null , 2 )}< / pre>
157+ < / div>
158+ )}
159+ < button onClick= {() => postMessage ({ foo: " bar" })}> Send< / button>
160+ < / div>
161+ )}
162+ < / WebWorker>
163+ )
164+ ```
165+
166+ > Note: the Worker must still implement JSON (de)serialization on its own end.
167+
141168## Helper components
142169
143170` <WebWorker> ` provides several helper components that make your JSX even more declarative.
0 commit comments