I’ve used several plugins such as axios for easier processing data via AJAX, but later I came across problems with these plugins – such as unable to provide the correct headers, unable to create a form data with multipart, and a bunch of other restrictions that made me just want to go back to the one that worked – fetch() method. The fetch() method is very powerful and can stay consistent through out its usage, but then with this method – our codes could look very long or hard to manage – so I’ve decided to come up with a helper function that simply wraps that fetch() method into a function. This wrapper function accepts 3 parameters: 1.) Object – which could be the state, or any object {} data, 2.) URL – where we want to post our request, and 3.) Callback which allows us to process the response data from the server.
Create a file helpers.js then add the following lines.
export function ajax(object, url, callback) { let formData = new FormData(); Object.keys(object).map(function(key) { return formData.append(key, object[key]); }); return fetch(url, { method: 'POST', body: formData }) .then((response) => response.json()) .then((responseJson) => { callback(responseJson); }) .catch((error) => { console.error(error); }); }
Then import it like so:
import { ajax} from ‘./helpers’
Sample usage:
ajax(this.state, 'http://example.com/api', function(response){ if(response.status === 1){ alert(response.msg); } else { alert(response.msg); } });
Sample usage in a Component with Form Inputs:
import React, { Component } from 'react'; import { ajax } from '../helpers'; export default class Apply extends Component { constructor(props) { super(props); this.state = { is_loading: false, errors: "" } } onChange = (e) => { var state = this.state; state[e.target.name] = e.target.value; this.setState(state); } onSubmit = (e) => { e.preventDefault(); ajax(this.state, 'http://example.com/api', function(response){ if(response.status === 1){ alert(response.msg); } else { alert(response.msg); } }); } render() { return ( <div className="container"> <div className="col-md-4 p-0"> <div className="form-group"> <label htmlFor="first_name">First Name</label> <input type="text" className="form-control" name="first_name" id="first_name" onChange={this.onChange} /> </div> <div className="form-group"> <label htmlFor="last_name">Last Name</label> <input type="text" className="form-control" name="last_name" id="last_name" onChange={this.onChange} /> </div> <div className="form-group"> <label htmlFor="email">Email</label> <input type="email" className="form-control" name="email" id="email" onChange={this.onChange} /> </div> <div className="form-group"> <label htmlFor="phone">Phone Number</label> <input type="text" className="form-control" name="phone" id="phone" onChange={this.onChange} /> </div> </div> <button className="btn btn-default" onClick={this.onSubmit}>Submit</button> </div> ) } }