0

I have Django and react app and I have to show some image as a campaign depending on current url.

On each page, there will be axios get request call to api and react will receive image and show the image on top.

to implement this I created function

let path_name = window.location.pathname;

const CampaignImageFetch = (url) => {
  if (!url) return "";
  return async () =>
    await axios({
      method: "get",
      url: process.env.REACT_APP_BASE_URL + "campaignpopup" + path_name,
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
        return res;
      })
      .catch((e) => {
        return e;
      });
};

To implement this on every page, I have to call this function from every page and will have to load Image component on every page. Is there any way I can implement this without adding the code on every page?

Anonymous
  • 77
  • 8
  • Have your code in app.js – Bhojendra Rauniyar Mar 23 '23 at 01:50
  • Does this answer your question? [how to listen for route change in react-router-dom v6](https://stackoverflow.com/q/70646421/283366) – Phil Mar 23 '23 at 01:53
  • every page?what mean?every block or every route?if you need init images in spa,you should request once,and pass json data every block,so improve it on server side. – Mee Mar 23 '23 at 01:55
  • @Mee Every route. on backend I have list of images and lot of conditions whether this image should show on given url, thats why I have to call API to decide whether this image is needed for that url. – Anonymous Mar 23 '23 at 02:26

1 Answers1

0

You can try putting the code at the app level within a useEffect that listens on route changes.

Otherwise, you could make a component that wraps your page components and use that. For example:

const CampaignImageFetch = ({ children }) => {
  const [image, setImage] = useState();

  useEffect(() => {
    // fetch and call setImage(response);
  }, []);

  return (
    <>
      {children}
      <ImageComponent image={image} />
    </>
  );
}

And in your page component:

const Page1 = () => {
  return (
    <CampaignImageFetch>
      <Page1Components />
    </CampaignImageFetch>

  );
}
Arthur
  • 2,622
  • 4
  • 28
  • 46