Minimal API Connector for react
Don’t waste your time by finding react version of your favorite javascript package, keep control of your API
now.
Documentation: You can find the react-aptor documentation on the website.
Most packages are developed separately in JavaScript for increasing generality being library/framework agnostic.
Connecting vanilla third parties to react is not a routine task especially those that need to change the DOM. On the other hand, these packages might be developed by different teams, hence development progress can be one step behind of the original or even be terminated at any time. Also, wrong abstraction or bad design patterns may interrupt the progress of these react-something
packages.
If you are still not convinced you can read this article
Other Concerns:
We strive to solve all mentioned problems at once and for all.
Connect your react app to any third party in three-step
useAptor
import Something from 'some-third-party';
export default function instantiate(node, params) {
return new Something(node, params);
}
This function will return an instance of the third-party package. You have access to node (DOM-node*) and params.
The
node
is passed by react-aptor as a reference to DOM that is occasionally used as a wrapper for embedding UI. The DOM-node* will become more clear in the third step.The
params
are optional parameters that are passed by react-aptor and define by you. see the third step. The params will be passed by you and will be more clear in third step.name this file construct.js as convention ✨.
export default function getAPI(instance, params) {
// return corresponding API Object
return () => ({
api_key: () => {
/* api definition using instance and params */
console.log(instance);
},
});
}
The react-aptor will pass the latest instance of your third-party which has been defined in the first step by instantiate function along with params to getAPI function.
The
instance
is returned instance of your third-party. Technically it is exactly going to be instantiate(node, params)The
params
are optional parameters that are passed by react-aptor and define by you. see the third step. The params will be passed by you and will be more clear in third step.name this file api.js as convention ✨.
useAptor
import useAptor from 'react-aptor';
import getAPI from './api';
import instantiate from './construct';
const Connector = (props, ref) => {
const aptorRef = useAptor(ref, {
getAPI,
instantiate,
/* params: anything */
});
return <div ref={aptorRef} />;
};
export default React.forwardRef(Connector);
name this file connector.jsx as convention ✨ If you are using react 17 or newer version, you can also name it connector.js
useAptor in one look
const aptorRef = useAptor(ref, configuration, deps);
ref For the connection phase, you need to define a forwardRef component. The useAptor
hook needs forwarded-ref as the first argument, this is necessary to bind all your defined api to this ref.
configuration As the configuration argument you need to pass defined instantiate (defined in the first step ☝️), getAPI (defined in the second step ☝️) and your custom params argument. The useAptor hook will return you a ref (aptorRef
) which you can bind to your DOM node.
The
params
doesn’t have any limitation, it can be any arbitrary type e.g. undefined, number, string or an object containing all of them. The params will be then passed to your instantiate and getAPI function, as you saw in the first and second steps. Params is the best place to connect props to your low-level api it means ”No Need” for extra function generation 🥳
deps Is the same as Dependencies array default value is []
but you can override it as the third and lat argument of useAptor. It maybe needed in situation which you want to force re-instantiate by some prop change. It will use shallow comparison (as react do) for deps array and will call your instantiate
& getApI
in a row.
const Main = () => {
const ref = createRef();
const apiKeyHandler = () => {
if (ref.current) {
ref.current.api_key();
}
};
return (
<div>
<Connector ref={ref} />
<Button onClick={apiKeyHandler}>api call</Button>
</div>
);
};
Pass createRef to the Connector component (made in the third step), and then you can access all of the APIs inside ref.current
function call can be much more readable with optional chaining & related babel plugin
const apiKeyHandler = () => ref.current?.api_key();
In case you need
ref.current
more than one time, it is a good idea to rename it at the first place
const apiKeyHandler = () => {
const { current: api } = ref; // store ref.current in `api`
if (api) {
api.api_key();
}
};
Cause the default value for ref can be undefined (in createRef) and null (in useRef) Typescript will complain about possibility for not-existence of apis. see more. In normal world react will bind your API to given ref after the Connector mount
If you’re using ref in useEffect or somewhere which is guaranteed to have the ref bounded to values, you can return proxy object in your getAPI function to bind all api functions simultaneously.
export default function getAPI(thirdParty, params) {
if (!thirdParty)
return () =>
new Proxy(
{},
{
get: (_, prop) => {
// Possible to mock differently for different props
return noop;
},
}
);
return () => ({
api_key() {
// third-party is defined here for sure :)
console.log(thirdParty);
},
});
}
You can access all of you apis via
this
keyword
export default function getAPI(sound, params) {
return () => ({
_state() {
return sound.getState();
},
play() {
if (this._state() === 'LOADED') sound.play();
},
});
}
It’s better to start name of this internal functions with
_
this
problem in API objectIn a case you see this keyword usage in third-party API you must specifying this
something other than returned API object. The following examples is for howler integration using react-aptor:
{
// ❌ It doesn't work
state: howler.state,
// 🆗 this is Okay
state: howler.state.bind(howler),
// 🆗 this is also Okay
state: () => howler.state(),
// 🆗 this is also Okay, too
state() {
return howler.state();
}
}
You can use something like the follwing:
export type APITypes = ReturnType<ReturnType<typeof getAPI>>;
useEffect
and proper deps
arraySee all in action in raptor-howler-example
required
The react useRef or createRef ref instance which has been passed throw react.forwardRef method. your api will be stored in this ref.
required
required
function(node, params): Instance
A function that receives probable bounded-node and params. It then returns an instance of your third-party.
function(previousInstance, params): void
A function that receives previous created instance and params. It is useful when you want to perform the cleanup before new instance creation. e.g. remove event listeners, free up allocated memories, destroy internally & etc
required
function(Instance, params): ApiObject
A function which receives instance of you third-party and params. It then returns a key-value pair object for api handlers.
any
Params can have any arbitrary type and can be used with props or pre-defined options.
[]
React dependencies array for re-instantiating your third-party-packages. It will call instantiate
with latest node, params when ever shallow comparison for with the previous deps array finds inequality.
🎨 Designer (BTC): bc1q9fahyct3lrdz47pjf4kfxvsyum2dm74v2hv9xl
💻 Developer/Maintainer (BTC): bc1qq8qq63ex7svkkjdjn5axu8angfxytvs83nlujk
Author: amirHossein-Ebrahimi
Download Link: Download The Source Code
Official Website: https://github.com/amirHossein-Ebrahimi/react-aptor
#react #api #javascript #web-development #webdev