I want to refactor the inner fn
of this.setState(fn)
to a static method that lives inside the Utils
class, Utils.createTargetDict
. I cannot wrap my head around how to get the the target
parameter's argument from register
into my newly created Utils.createTargetDict
. I this is a FP technique requires currying but i just cannot figure it out.
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {targets: {}}
}
get engine() {
return {
state: this.state,
register: target => {
this.setState(ps => {
return {
targets: {
...ps.targets,
...Utils.createElement(target),
},
};
});
},
}
}
}
const myComp = new MyComponent();
const engi = myComp.engine;
engi.register({current: {foo: '1', bar: 'a'}});
From:
register: target => {
this.setState(ps => {
return {
targets: {
...ps.targets,
...Utils.createElement(target),
},
};
});
},
To:
register: target => {
this.setState(Utils.createTargetDict);
},
Utils
class Utils {
static createTargetDict(ps) {
return {
targets: {
...ps.targets,
...Utils.createElement(target), // this will fail bc target doesn't exist
},
};
}
static key() {
let d, r;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
r = (new Date().getTime() + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
}
static createElement(target) {
const key = Utils.key();
return {
[key]: {
...target,
current: {
...target.current,
key: key,
visibility: false,
},
},
};
}
}