I’m using react’s componentDidMount()
, which holds a lot of code and does two callbacks. Eventually, in the inner most callback (i.e., the second one), I execute this.setState({})
.
Minimal code
class App extends React.Component {
constructor(props) {
super(props);
this.state = { data: {} };
}
requests() {
fooCallback.request({ data: { query: userQuery } }).subscribe(({ jsonResp1 }) => {
// 100 lines of data processing with jsonResp1
// second Callback
barCallback.request({ data: { string: userString } }).subscribe(({ jsonResp2 }) => {
// 200 lines of data processing with jsonResp2
this.setState({ data: processedData })
});
});
componentDidMount() {
this.requests();
}
}
render() {
// ...
return (
// ...
);
}
}
Since the request()
method is very huge it bloats my main container component App. I’ve already tried to create an external js file (default export function ...
) and imported that in my App.js. Yet, this was not possible probably due to the asynchron nature of the method.
Is it somehow possible to reduce my App.js?
Edit
What I tried in many variants is to create an external.js file:
external.js
export default async () => {
return fooCallback.request({ data: { query: userQuery } }).subscribe(({ jsonResp1 }) => {
// 100 lines of data processing with jsonResp1
// second Callback
barCallback.request({ data: { string: userString } }).subscribe(({ jsonResp2 }) => {
// 200 lines of data processing with jsonResp2
return processedData
});
return barCallback;
});
... and then to import it
App.js
import getData from './js/getData.js'
// ...
async componentDidMount() {
const response = await this.getData()
this.setState({data: response})
}
Yet, no success. Is the only way to create a class component, maybe?