-
Notifications
You must be signed in to change notification settings - Fork 3
07 Active Record
JP Barbosa edited this page Apr 16, 2021
·
1 revision
code ./src/pages/Record/index.tsx
import { useState } from 'react';
...
export const RecordIndex = <T extends Record>({
...
}: RecordIndexProps<T>) => {
const [activeRecord, setActiveRecord] = useState<T>(emptyRecord);
const { ... } = useFetch<T>(...);
...
return (
<div className="page">
<div className="content">
<RecordList<T>
...
emptyRecord={emptyRecord}
activeRecord={activeRecord}
setActiveRecord={setActiveRecord}
/>
<RecordMutations<T>
...
activeRecord={activeRecord}
/>
</div>
</div>
);
};
code ./src/interfaces/PagesProps.ts
...
export interface RecordListProps<T> {
...
emptyRecord: T;
activeRecord: T;
setActiveRecord: Function;
}
...
code ./src/pages/Record/List.tsx
...
export const RecordList = <T extends Record>({
...
emptyRecord,
activeRecord,
setActiveRecord,
}: RecordListProps<T>) => {
...
return (
<div className="list">
<h2>{page}</h2>
<button className="bt-new" onClick={() => setActiveRecord(emptyRecord)}>
New
</button>
<ul>
{records.map((record) => (
<li
key={record.id}
className={record.id === activeRecord?.id ? 'active' : ''}
onClick={() => setActiveRecord(record)}
>
<ListItem record={record} />
</li>
))}
</ul>
</div>
);
};
code ./src/pages/Record/Mutations.tsx
...
import { RecordEdit } from './Edit';
export const RecordMutations = <...>(...) => {
return (
<div className="mutations">
{activeRecord.id ? (
<RecordEdit<T> FormFields={FormFields} activeRecord={activeRecord} />
) : (
<RecordNew<T> FormFields={FormFields} activeRecord={activeRecord} />
)}
</div>
);
};
code ./src/interfaces/PagesProps.ts
...
export interface RecordEditProps<T> {
FormFields: React.FC<FormFieldsProps<T>>;
activeRecord: T;
}
...
code ./src/pages/Record/Edit.tsx
import { Record } from '../../interfaces/RecordEntities';
import { RecordEditProps } from '../../interfaces/PagesProps';
import { RecordForm } from './Form';
export const RecordEdit = <T extends Record>({
FormFields,
activeRecord,
}: RecordEditProps<T>) => {
return (
<div className="edit">
<h2>Edit</h2>
<RecordForm FormFields={FormFields} activeRecord={activeRecord} />
</div>
);
};
code ./src/pages/Record/Form.tsx
import { useEffect } from 'react';
...
export const RecordForm = <...>(...) => {
const { formState, setFormState, handleChange } = useForm<T>(activeRecord);
useEffect(() => {
if (activeRecord) {
setFormState(activeRecord);
}
}, [setFormState, activeRecord]);
...
};
git add .
git commit -m "Active Record"