skip to Main Content

I am using two URLs:

  1. localhost:3000/content
  2. localhost:300/content/<projectId>.

My routes are:

<Route
  path="/content"
  element={
    <RequireAuth>
      <ContentPage />
    </RequireAuth>
  }
/>

<Route
  path="/content/:projectId"
  element={
    <RequireAuth>
      <ProjectPage />
    </RequireAuth>
  }
/>

When I am going sequentially, its working perfectly. But when I am navigating to some pages and coming back, its not able to load the blog posts under [2] URL. These blogs are coming from a backend in terms of an array and I am storing them using useState to render as required under the return section using the following code:

import React, { useEffect, useState } from "react";
import { useLocation, useSearchParams } from "react-router-dom";


const ProjectPage = () => {
  const { projectId } = useParams();
  const [pagesname, setPagesname] = useState([]);
  const [dashboarderror, setDashboarderror] = useState();
  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const pageId = searchParams.get("pageId");

  useEffect(() => {
    async function fetchData() {
      try {
        const authconfig = {
          headers: {
            "Content-Type": "application/json",
            Authorization:
              "Bearer " + JSON.parse(localStorage.getItem("user_token")).token,
          },
        };
        const res = await axios.get(
          dashboardURL,
          authconfig
        );
        for (let i = 0; i < res.data.matrixDetails[2].projects.length; i++) {
          if (
            res.data.matrixDetails[2].projects[i].projectTypeName ===
            location.state
          ) {
            setPagesname(res.data.matrixDetails[2].projects[i].pages);
            );
          }
        }
        } catch (e) {
        setDashboarderror(e);
      }
    }
    fetchData();
  }, [location]);    // location is available but useEffect is not loading on URL change

  return (
  <Box>
   {pagesname.map((sname) => {
     return (
       <div key={sname.pageKeyId}>
         <Button
           style={{
            textTransform: "none",
            color: "#546e7a",
            backgroundColor: "transparent",
            padding: "2px",
          }}
          onClick={() =>
            setSearchParams({ pageId: sname.pageKeyId })
          }
        >
          <DataTreeView
            treeItems={pagesname}
            pgCode={sname.pageKeyId}
          />
        </Button>
      </div>
     {pageId && <PageView pageId={pageId} />}
    </Box>
    );
  })}

    )
}

I am using MUI TreeView to display the blogs sequentially in the sidebar.

enter image description here

In the above image, Web Development (as mentioned in 1 in the above image) is the name of the Project which is coming from the backend and I am storing that in the localStorage. So even if I am switching through multiple pages, if useState is not having that value I can call it from localStorage and its working well.

But I am not storing the pages (as mentioned in [2] in the above image) in the localStorage, hence if I am refreshing the URL or switching the URL, then after coming to this page (localhost:3000/content/<projectId>), I can only see the Project Name, not the Pages. And even though useEffect is used with location, its not able to fetch them again.

Is there any way to fetch the data when the URL will change ?

2

Answers


  1. Chosen as BEST ANSWER

    After some debugging, I found that my condition was wrong. After a page url change the location.state was changing which was breaking the if condition.

    Old code
    for (let i = 0; i < res.data.matrixDetails[2].projects.length; i++) {
      if (
        res.data.matrixDetails[2].projects[i].projectTypeName ===
        location.state
      ) {
        setPagesname(res.data.matrixDetails[2].projects[i].pages);
        );
      }
    }
    

    When the page was loading for the first time, I used to save a localStorage property proName. Hence just get that to validate and it started working.

    New Code

    for (let i = 0; i < res.data.matrixDetails[2].projects.length; i++) {
      const spName = JSON.parse(localStorage.getItem("proName"));
      if (
        res.data.matrixDetails[2].projects[i].projectTypeName ===
        location.state || proName === res.data.matrixDetails[2].projects[i].projectTypeName
      ) {
        setPagesname(res.data.matrixDetails[2].projects[i].pages);
        );
      }
    }
    

  2. I’d have to dig into the specifics of react-router-dom to say for sure, but it’s possible that the location object itself doesn’t change, just as window.location doesn’t change as you navigate around a SPA. Try changing the dependency to location.href or location.pathname.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search