export const useTodoService = ({ baseUrl, todoId }) => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const fetch = async () => {
setLoading(true);
try {
const d = await asJson(`${baseUrl}/todos/${todoId}`);
setData(d);
} catch (e) {
setError(e);
}
setLoading(false);
};
return [
{ loading, data, error },
{ fetch },
];
};
Naming convention
{ error, data, loading }
state and API to perform operations with this service (fetch
, update
, refetch
, etc)data
+ setData
, error
+ setError
use
, etc)export const useModalController = () => {
const [isOpen, setIsOpen] = useState(false);
const closeDialog = () => {
setIsOpen(false);
};
const openDialog = () => {
setIsOpen(true);
};
return [isOpen, { closeDialog, openDialog }];
};
isOpen
+ setIsOpen
import { useModalController } from './controllers';
const App = () => {
const [isModalOpen, { openModal, closeModal }] = useModalController(false);
return (
<>
<Button onClick={openModal}>Open Modal</Button>
{isModalOpen && (
<Modal
onClose={closeModal}
heading="yo!"
actions={[{ text: 'Close', onClick: closeModal }]}
>
content
</Modal>
)}
</>
);
};