Step 22: Protect Edit View

When a user opens the QuickNotes app, they will see the homepage. When they click on the “Add Note” button or an “Edit” action icon, they will be redirected to the Edit view. However, they can also use the browser URL address to navigate to the Edit page. In most applications, this would be the desired behavior. Here, however, it does not make sense to directly go to the Edit page!

To fix this issue, let’s update the pages/Edit.jsx as follows:

 function Edit(props) {
   const { edit, remove } = props;
   const navigate = useNavigate();
   const location = useLocation();
-  const { id, text: _text, title: _title, mode } = location.state;

+  const [id, setId] = useState("");
   const [title, setTitle] = useState("");
   const [text, setText] = useState("");
+  const [mode, setMode] = useState("");

-  useEffect(() => {
-    if (_text !== text) {
-      setText(_text);
-    }
- 
-    if (_title !== title) {
-      setTitle(_title);
-    }
-  }, [_text, _title]);

+  useEffect(() => {
+    if (location.state === null) {
+      navigate("/", { replace: true });
+    } else {
+      location.state.id !== id && setId(location.state.id);
+      location.state.title !== title && setTitle(location.state.title);
+      location.state.text !== text && setText(location.state.text);
+      location.state.mode !== mode && setMode(location.state.mode);
+    }
+  }, [location.state]);

Observe how the app works now: