Our team is new to React, and we are learning best practices as we go.
One of the teams biggest concerns right now is how we are handling our API calls and dealing with state. We are following Reacts advice which is --> "Lift Up State". This all works, but it is causing our higher level components to be large and often handle API calls that I don't think it should have to be concerned with.
The below example is very simplified. In reality each of these fetch statements will need to set the state of a few different things, such as loadingForA, statusForA, dataForA.... This leads quickly leads to a very large state and a lot of passing down of props
Are there any design patterns that can be used here? I have looked into "Render Props", but this seems to be hard to use for event triggered API fetches
Example:
class ExampleComponent extends Component {
render(){
return(
<Dropdown
onChange = {this.props.handleChange}
/>
<p>{this.props.dataA}</p>
<p>{this.props.dataB}</p>
<p>{this.props.dataC}</p>
)
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
date: '',
dataA: {},
dataB: {},
dataC: {}
};
}
handleChangeA() {
fetch(someURL)
.then(
this.setState({dataA: fetchResult});
)
}
handleChangeB() {
fetch(someURL)
.then(
this.setState({dataB: fetchResult});
)
}
handleChangeC() {
fetch(someURL)
.then(
this.setState({dataC: fetchResult});
)
}
render(){
return(
<ExampleComponentA
handleChange = {this.handleChangeA}
date = {this.date}
dataA = {this.dataA}
dataB = {this.dataB}
dataC = {this.dataC}
/>
<ExampleComponent
handleChange = {this.handleChangeB}
date = {this.date}
dataA = {this.dataA}
dataB = {this.dataB}
dataC = {this.dataC}
/>
<ExampleComponent
handleChange = {this.handleChangeC}
date = {this.date}
dataA = {this.dataA}
dataB = {this.dataB}
dataC = {this.dataC}
/>
);
}
}
Aucun commentaire:
Enregistrer un commentaire