Creating a AJAX Helper Function in ReactJS

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.

Then import it like so:

import { ajax} from './helpers'

Sample usage:

Sample usage in a Component with Form Inputs: