0

I am checking if a page or post exists, if not I am redirecting back to the homepage. This works fine, however when I am "click" inside the browser on the "Previous arrow" it will redirect that page over and over again. Is there a solution for this? Have someone ever faced this issue with React Router?

import { useEffect, useState } from "react";
import { useParams, Navigate } from "react-router-dom";

import NotFound from "components/Page404";

import SanityClient from "sanity.client";
import { getImage, TheContent } from "sanity.helpers";

import Loader from "components/Loader";

const BlogSinglePost = (props) => {
  const [singlePost, setSinglePost] = useState(null);
  const { slug } = useParams();
  const { projectId, dataset } = SanityClient.clientConfig;

  useEffect(() => {
    const singlePostQuery = `
      *[slug.current == $slug] {
        _id,
        title,
        slug,
        mainImage {
          alt,
          asset -> {
            _id,
            url
          }
        },
        body,
        "name": author->name,
        "authorImage": author->image,
        "authorImageAlt": author->image
      }
    `;

    SanityClient.fetch(singlePostQuery, { slug })
      .then((data) => setSinglePost(data.length === 0 ? [] : data))
      .catch(console.error);
  }, [slug]);

  if (!singlePost) return <Loader />;

  if (Object.keys(singlePost).length === 0) return <Navigate to="/" />;

  return (
    <>
      {singlePost &&
        singlePost.map((post) => (
          <div key={post._id}>
            <h2>{post.title}</h2>
            <img src={getImage(post.authorImage).width(100).url()} alt="" />
            <h4>{post.name}</h4>
            {post.mainImage && (
              <img
                src={getImage(post.mainImage).width(860).url()}
                alt={post.mainImage.alt}
              />
            )}
            <TheContent
              blocks={post.body}
              projectId={projectId}
              dataset={dataset}
            />
          </div>
        ))}
    </>
  );
};

export default BlogSinglePost;
Galanthus
  • 590
  • 3
  • 19

0 Answers0