Frontend: CSS modules, Zustand + URL sync
This commit is contained in:
38
frontend/src/hooks/urlSync.ts
Normal file
38
frontend/src/hooks/urlSync.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useEffect } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import useNavState from "../store/navStore";
|
||||
|
||||
export const useUrlSync = () => {
|
||||
const navigate = useNavigate();
|
||||
const { celexId: paramCelexId, articleId: paramArticleId } = useParams();
|
||||
const { articleId, celexId, setArticleId, setCelexId } = useNavState();
|
||||
|
||||
// Effect to read from URL when URL changes
|
||||
useEffect(() => {
|
||||
if (paramCelexId && paramCelexId !== celexId) {
|
||||
setCelexId(paramCelexId);
|
||||
}
|
||||
|
||||
if (paramArticleId) {
|
||||
const parsedArticleId = paramArticleId ? parseInt(paramArticleId) : null;
|
||||
if (parsedArticleId && parsedArticleId !== articleId) {
|
||||
setArticleId(parsedArticleId);
|
||||
}
|
||||
} else {
|
||||
// If no articleId in URL, reset Zustand state
|
||||
setArticleId(null);
|
||||
}
|
||||
}, [paramArticleId, paramArticleId]);
|
||||
|
||||
// Update the URL when Zustand changes
|
||||
useEffect(() => {
|
||||
if (celexId === null) {
|
||||
return;
|
||||
}
|
||||
let targetUrl = `/${celexId}`;
|
||||
if (articleId !== null) {
|
||||
targetUrl += `/articles/${articleId}`;
|
||||
}
|
||||
navigate(targetUrl, { replace: true });
|
||||
}, [navigate, celexId, articleId]); // Only sync URL when Zustand changes
|
||||
};
|
||||
Reference in New Issue
Block a user