@toloka-dev/tbx-external-field-client
Version:
Library designed to facilitate communication and configuration management between TBX and an external app
43 lines (40 loc) • 1.47 kB
JavaScript
import { useReducer, useEffect } from 'react';
import { createFieldExternalConnection } from '../utils/create-field-external-connection.js';
const useExternalFieldConnection = () => {
const params = new URLSearchParams(window.location.search);
const theme = (params.get('theme') ?? 'light');
const [state, setState] = useReducer((state, newState) => ({
...state,
...newState,
}), { theme, error: null, api: null, value: null, config: null });
useEffect(() => {
setState({ error: null });
const connections = createFieldExternalConnection({
onChangeConfig: (changedConfig) => {
setState({ config: changedConfig });
},
onChangeValue: (changedValue) => {
setState({ value: changedValue });
},
onChangeTheme: (changedTheme) => {
setState({ theme: changedTheme });
},
});
connections.promise
.then((api) => {
const fieldApi = api;
return Promise.all([Promise.resolve(api), fieldApi.getConfig(), fieldApi.getValue()]);
})
.then(([api, config, value]) => {
setState({ api, config, value });
})
.catch((error) => {
setState({ error });
});
return () => {
connections.destroy();
};
}, []);
return state;
};
export { useExternalFieldConnection };