@@ -17,6 +17,7 @@ any messages or errors it sends, as well as the `postMessage` handler.
17
17
- Provides easy access to the last message ` data ` and last ` error `
18
18
- Provides ` postMessage ` to send messages to the Web Worker
19
19
- Provides ` updatedAt ` and ` lastPostAt ` metadata
20
+ - Accepts ` parser ` and ` serializer ` for automatic message (de)serialization
20
21
- Accepts ` onMessage ` and ` onError ` callbacks
21
22
22
23
> 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 = () => (
80
81
81
82
- ` url ` {string} (required) Public url to the Web Worker file (or path relative to the root of your domain)
82
83
- ` options ` {Object} Options passed to the Worker constructor
84
+ - ` parser ` {Function} Transforms incoming messages (not errors)
85
+ - ` serializer ` {Function} Transforms ` postMessage ` payload before sending
83
86
- ` onMessage ` {Function} Callback function invoked when a message is received, passing message data as argument
84
87
- ` onError ` {Function} Callback function invoked when an error is received, passing error object as argument
85
88
@@ -138,6 +141,30 @@ const MyComponent = () => (
138
141
)
139
142
```
140
143
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
+
141
168
## Helper components
142
169
143
170
` <WebWorker> ` provides several helper components that make your JSX even more declarative.
0 commit comments