I currently have a couple of React components that looks similar in terms of functionality. They all have similar methods used to fetch data a server and update each component's state by making an API to different endpoints.
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import AppService from '../lib/service';
class Factorial extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
}
}
getNext() {
AppService.getNextFactorial().then(data => {
this.setState({ value: data.data.gen })
})
}
resetFactorial() {
AppService.resetNextFactorial().then(data => {
this.setState({ value: data.data.reset })
})
}
render() {
return (
<div className={'functionsWrapper'}>
<h2> Factorial Sequence Generator </h2>
<p> Click to get the next value in the sequence </p>
<button onClick={() => this.getNext()}> Get Next</button>
<button onClick={() => this.resetFactorial()}> Reset </button>
<div>
<input type="text" id="body" defaultValue={this.state.value} name="body" className="form-input" />
</div>
</div>
)
}
}
export default withRouter(Factorial);
import React, { Component } from 'react';
import AppService from '../lib/service';
class Fibonacci extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
}
}
getNext() {
AppService.getNextFibonacci().then(data => {
this.setState({ value: data.data.gen })
})
}
resetFibonacci() {
AppService.resetNextFibonacci().then(data => {
this.setState({ value: data.data.reset })
})
}
render() {
return (
<div className={'functionsWrapper'}>
<h2> Fibonacci Sequence Generator </h2>
<p> Click to get the next value in the sequence </p>
<button onClick={() => this.getNext()}> Get Next</button>
<button onClick={() => this.resetFibonacci()}> Reset </button>
<div>
<input type="text" id="body" defaultValue={this.state.value} name="body" className="form-input" />
</div>
</div>
)
}
}
export default Fibonacci;
What I want to achieve is to be able split the functions of each component and make it reusable so that I can have a generic approach