I'm a beginner in ReactJS, and I'm trying to improve the writing of my codes, and I ended up getting to the API calls part, I want to improve the reusability of my API calls and set them with a specific folder something like utils / APIcalls.js but I do not know the best way and the correct way to do this, I have the following API call getItems():
Home.jsx
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
'items': [],
isLoading: false,
error: null,
};
}
componentDidMount() {
this.getItems()
this.refresh = setInterval(() => this.getItems(), 100000);
}
componentWillUnmount() {
clearInterval(this.refresh)
}
getItems() {
this.setState({ 'isLoading': true });
fetch('https://xxx/api/article/')
.then(results => {
if (results.ok) {
return results.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(results => this.setState({ 'items': results, 'isLoading': false }))
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
const { isLoading, error } = this.state;
if (error) {
return <p>{error.message}</p>;
}
if (isLoading) {
return <Loading />
}
return (
<div className="container" >
<div className="row align-items-start">
<Principal items={this.state.items} />
</div>
<hr />
<div className="row align-items-start">
<Secondary items={this.state.items} />
</div>
</div>
);
}
}
I use the same call in multiple places, is there any way to set these calls globally, and call them more easily elsewhere in the code?
To solve this problem problem I used axios to create reusable functions:
I created a folder called by utils, inside that folder I created a file called by apiConfig.js and apiCalls.js:
import API from './apiConfig'
export default {
getArticles: () => {
return API.get('article')
.then(res => res.data)
},
getUser: () => {
return API.get('user')
.then(res => res.data)
}
}
After that, I call that functions in the components using that way:
componentDidMount() {
this.getItems()
}
getItems() {
this.setState({ 'isLoading': true });
API.getArticles().then(items => this.setState({ items, 'isLoading': false }))
.catch(error => this.setState({ error, isLoading: false }));
}
fetch+ firstthento a separate function and use it here/api/index.js) if there is not a huge number of such functions (up to 10-15). If there are more - try to group them somehow (for example domain-drivenly -/api/user.js,/api/products.js, etc)actionsthat returnthunks, although I may be biased because that's the structure I learned initially with react/redux