drf-react-by-schema
Version:
Components and Tools for building a React App having Django Rest Framework (DRF) as server
68 lines (67 loc) • 3.42 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useOptionsAC = void 0;
const react_1 = require("react");
const axios_1 = __importDefault(require("axios"));
const APIWrapperContext_1 = require("../../../context/APIWrapperContext");
const useOptionsAC = ({ columns, schema, optionsACExternal, indexField, addExistingModel, }) => {
const { getAutoComplete } = (0, APIWrapperContext_1.useAPIWrapper)();
const [optionsAC, setOptionsAC] = (0, react_1.useState)({});
const updateOptionsAC = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
var _a;
const newOptionsAC = {};
for (const col of columns) {
if (optionsACExternal && col.field in optionsACExternal) {
newOptionsAC[col.field] = optionsACExternal[col.field];
continue;
}
if (!schema[col.field]) {
continue;
}
const fieldSchema = schema[col.field];
if (['field', 'nested object'].includes(fieldSchema.type) && !(col.field in newOptionsAC)) {
const options = yield getAutoComplete(col.field);
if (!axios_1.default.isAxiosError(options)) {
newOptionsAC[col.field] = options;
continue;
}
console.log(`Couldn't load autocomplete options from '${col.field}'`);
continue;
}
if (fieldSchema.type === 'choice' && !(col.field in newOptionsAC)) {
newOptionsAC[col.field] = fieldSchema.choices || [];
continue;
}
if (fieldSchema.type === 'list' && !(col.field in newOptionsAC)) {
newOptionsAC[col.field] = ((_a = fieldSchema.child) === null || _a === void 0 ? void 0 : _a.choices) || [];
continue;
}
if (col.field === indexField && addExistingModel && !newOptionsAC[col.field]) {
const options = yield getAutoComplete(addExistingModel);
if (!axios_1.default.isAxiosError(options)) {
newOptionsAC[col.field] = options;
continue;
}
}
}
setOptionsAC(newOptionsAC);
}), [columns, schema, optionsACExternal, indexField, addExistingModel]);
(0, react_1.useEffect)(() => {
updateOptionsAC();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [columns]);
return { optionsAC, updateOptionsAC };
};
exports.useOptionsAC = useOptionsAC;