Ajax Component is an extendable React Component that gives you enter
and exit
classes
automatically as the component mounts, unmounts, and makes new API requests.
Install using npm install react-ajax-component
Example usage:
import { createElement } from 'react';
import AjaxComponent from 'react-ajax-component';
export default class ExampleView extends AjaxComponent {
apiEndpoint() {
return '/api/get-title'
}
render() {
return createElement('div', null, this.state.data.title);
}
}
Edit the config object like so:
import { config } from 'react-ajax-component';
config.apiMethod = 'GET';
-
apiMethod String (default:
'POST'
)
The type of method to fetch the API request. -
apiHeaders Object (default:
{ 'Content-Type': 'application/json' }
),
Headers to include in API requests.
-
timeout Number (default:
1000
)
Duration to hold theenter
andexit
classes. -
classNamePrefix String (default:
'is'
)
A string to append to the beginning of theenter
andexit
classes.
When building out an extended class, here are the methods that you will likely need to edit, depending on your needs.
-
shouldFetchData( nextProps: Object ): Boolean
Used to determine if a new API request should be made. IfshouldFetchData
returns true, the old state of the Component will be mock unmounted and new data will emulate the appearance of a new Component. -
resolveData( nextProps: Object ): Promise
The logic that handles making the API request. -
apiEndpoint( nextProps: Object ): String
The url to send API request to. -
apiPayload( nextProps: Object ): Object
The data to include in the API request. -
onDataUpdate()
A function to be called after each API request has completed. -
renderError(): ReactElement | null
A React render function that will be used in the event of an API error.
Note:this.state.data
will benull
andthis.state.errors
will betrue
. -
renderLoader(): ReactElement | null
A React render function that will be used before the API has responded.
Note:this.state.data
will benull
at this point.