11// @flow
22
3- import React from 'react' ;
4- import compileWasm from './compileWasm' ;
5- import type { WasmProps , WasmState , WasmParams } from './types' ;
6-
7- export default class Wasm extends React . Component < WasmProps , WasmState > {
8- static defaultProps = {
9- url : null ,
10- bufferSource : null ,
11- importObject : { }
12- } ;
13-
14- state = {
15- loading : true ,
16- error : null ,
17- data : null ,
18- // eslint-disable-next-line
19- prevProps : {
20- url : null ,
21- bufferSource : null
22- }
23- } ;
24-
25- static getDerivedStateFromProps ( props : WasmProps , state : WasmState ) {
26- const { url, bufferSource } = props ;
27-
28- if (
29- url && url !== state . prevProps . url ||
30- ! url && bufferSource !== state . prevProps . bufferSource
31- ) {
32- return {
33- loading : true ,
34- error : null ,
35- data : null ,
36- prevProps : {
37- url,
38- bufferSource
39- }
40- } ;
41- }
42-
43- return null ;
44- }
45-
46- componentDidMount ( ) {
47- const { url, bufferSource, importObject } = this . props ;
48-
49- this . loadModule ( { url, bufferSource, importObject } ) ;
50- }
51-
52- componentDidUpdate ( prevProps : WasmProps ) {
53- const { url , bufferSource , importObject } = this . props ;
54-
55- if (
56- url && url !== prevProps . url ||
57- ! url && bufferSource !== prevProps . bufferSource
58- ) {
59- this . loadModule ( { url, bufferSource, importObject } ) ;
60- }
61- }
62-
63- loadModule = ( {
64- url,
65- bufferSource,
66- importObject
67- } : WasmParams ) =>
68- compileWasm ( {
69- url,
70- bufferSource,
71- importObject
72- } )
73- . then ( ( { module, instance } ) => {
74- this . setState ( {
75- loading : false ,
76- error : null ,
77- data : {
78- module,
79- instance
80- }
81- } ) ;
82- } )
83- . catch ( error => {
84- this . setState ( {
85- loading : false ,
86- error,
87- data : null
88- } ) ;
89- } ) ;
90-
91- render ( ) {
92- const { children } = this . props ;
93- const { loading, error, data } = this . state ;
94-
95- return children ( { loading, error, data } ) ;
96- }
97- }
3+ import useWasm from './useWasm' ;
4+ import type { WasmProps } from './types' ;
5+
6+ const Wasm = ( { url, bufferSource, importObject, children } : WasmProps ) => {
7+ const state = useWasm ( {
8+ url,
9+ bufferSource,
10+ importObject
11+ } ) ;
12+
13+ return children ( state ) ;
14+ } ;
15+
16+ Wasm . defaultProps = {
17+ url : null ,
18+ bufferSource : null ,
19+ importObject : { }
20+ } ;
21+
22+ export default Wasm ;
0 commit comments