How could I chain helper methods in React?
I have a helper.js file with helper functions.
ie: (ps: bellow are just mundane methods to illustrate my issue for now)
//helper.js
export function handleLog(arg) {
return console.log(`App current state is: ${arg}`);
}
export function handleSlice(arr) {
return arr.slice(1, 2);
}
export function handleShuffle(arr) {
return arr.sort(() => Math.random() - 0.5);
}
I'm able to apply the methods to my React app as:
import { handleLog, handleSlice, handleShuffle } from "./helpers";
...
class Heros extends PureComponent {
constructor() {
super();
this.state = {
heros: ["Hulk", "Thor", "Aquaman", "Stan Lee"]
};
}
render() {
const { heros } = this.state;
const shuffledheros = handleShuffle(heros);
const strongestHero = handleSlice(shuffledheros);
handleLog(heros);
/* How could I chain 👇 */
// const strongestHero = handleShuffle(heros).handleSlice(heros);
return (
<>
<h1>Chained Helpers</h1>
Strongest: {strongestHero}
</>
);
}
}
How could I chain ie: handleShuffle(heros).handleSlice(heros) and so on?
- When chaining the second method it throws:
(0 , _helpers.handleSlice)(...).handleSlice is not a function
I've unsuccessfully attempted refactoring the helpers to:
const helpers = {
f1() { ...do something...; return this;},
f2() { ...do something...; return this;}
}
export default helpers
That didn't work either. Here is the full code