The pattern I've typically used is some container component is the launching point for a form. It has a list of data and the user clicks on one to edit it, which navigates to a form (modal or another page, whatever). The way I manage this logic is usually something like this
const query = useItemsQuery();
const [selectedItem, setSelectedItem] = useState<Item | null>(null);
function handlePickItemToEdit(item) {
setSelectedItem(item);
}
function handleSubmit() {
itemMutation.mutate(selectedItem, {
onSuccess() {
setSelecteditem(null);
}
});
}
if (selectedItem) {
return <ItemForm item={selectedItem} onSubmit={handleSubmit} />
}
// else display the list of items to pick one to edit
The thing is, this assumes the list will always load first, but what if the user navigates directly to the edit page via hard page refresh? What's a good way to initialize the form?
const {id} = useParams();
const serverItem = useItemQuery(id).data;
const [item, setItem] = useState<Item | null>(null);
useEffect(() => {
setItem(prev => prev ? prev : serverItem);
}, [serverItem]);
// ^ I hate doing stuff like this, seems super jank
Is there a better pattern to try instead? I hope this makes sense.