Reputation: 5
Some days ago, I did a question about Laravel, but now I will make a shot with Nodejs and React. The main goal is:
For this, I want to create a file with fetch functions, for later use. Is there a way to setup a fetch function in a file and reuse it?
import React, { Component } from 'react';
import { fetch_function } from './fetch_file';
class App extends Component {
constructor(props) {
super(props);
this.state = {
Items: [],
is_loaded: false,
}
url = "http://localhost:4000";
this.fetch_function(url, this.state, "Items");
}
componentDidMount() {
}
render() {
var { is_loaded, Items} = this.state;
const options_select_items = Items.map((Item, id) => {
return ({ value: Item.id, label: Item.Name })
})
return (
<Form>
<Form.Group as={Row} controlId="formHorizontalClientes">
<Form.Label column sm={3}>
Cliente
</Form.Label>
<Col sm={9}>
<Select
closeMenuOnSelect={true}
defaultValue={[system_default[0]]}
isMulti
options={options_select_items}
/>
</Col>
</Form.Group>
</Form>
);
}
}
export default App;
And this is the fetch_file
const fetch_function = (url, setState, param) => {
fetch(url)
.then(response => {
if (!response.ok) {
throw Error("Network failure")
}
return response;
})
.then(res => res.json())
.then(data => {
setState({
[param]: data
})
})
;
}
module.exports.fetch_function = fetch_function ;
Upvotes: 0
Views: 4511
Reputation: 164
Yes it is possible and highly advisable, especially if your project grows.
I suggest using axios, since it automatically returns JSON and is easier to use than the fetch API.
I also don't suggest to mutate the state in that file, since it will become a nightmare when maintaining and debugging the code.
Create a fetch.js
(or whatever you wanna call it)
import axios from 'axios';
const apiBaseURL = 'www.whatever.com'
export const GET = url => {
return axios.get(`${apiBaseURL}/${url}`);
}
// if need for headers etc.
const headers = 'some headers';
export const POST = (url, data) => {
return axios(`${apiBaseURL}/${url}`, {
method: 'POST',
headers,
data,
});
}
In the react component:
import the file at the top:
import { GET, POST } from './fetch.js';
In component method:
async getData(apiEndpoint) {
const { data: Items } = await GET(apiEndpoint);
if (Items) {
// Set data to state
this.setState({ Items });
}
else {
// error
}
}
The same can be achieved with the plain fetch API as well.
Upvotes: 4