Home > Back-end >  Query lost on page refresh in NextJS
Query lost on page refresh in NextJS

Time:04-03

router.query.title goes away when I refresh the page.

from what I found I have to use getServerSideProps but I don't know what to type on getServerSideProps. or is there any way to do it?

edit: I tried Yilmaz's solution and removed the as={} now it works. But query links too long now without using as={} any solution for this?

index.tsx

const Projects = () => {
  const [projects, setProjects] = useState(data);

  {projects.slice(0, loadMore).map((project) => (
          <Link
            key={project.id}
            href={{
              pathname: "/projects/"   project.title,
              query: {
                id: project.id,
                category: project.category,
                title: project.title,
                image: project.image.src,
                image1: project.image1.src,
                image2: project.image2.src,
                image3: project.image3.src,
                image4: project.image4.src,
                image5: project.image5.src,
              },
            }}
            as={"/projects/"   project.title}
            passHref={true}
          >
}

[id].tsx


import { GetServerSideProps } from "next";

export const getServerSideProps: GetServerSideProps = async (context) => {
  return {
    props: {},
  };
};

const Details = () => {
  const router = useRouter();

  return (
    <>
      <div className="single__page">
        <div className="single__header">
          <h2>{router.query.title}</h2>
        </div>
      </div>

CodePudding user response:

import { NextPageContext } from "next";


export const getServerSideProps: GetServerSideProps = async (context: NextPageContext) => { {
      const { query } = context;
      return { props: { query } };
    }

this will pass query to props. When you hover over query, ts will already infer its type as: const query: ParsedUrlQuery

in your component

const Details = (props) => {
  // this is object
  const {query}=props
  console.log(query)

  return (
    <>
      <div className="single__page">
        <div className="single__header">
          <h2></h2>
        </div>
      </div>

Second approach

const Details = () => {
  const [title,setTitle]=useState("")
  const router = useRouter();
  useEffect(() => {
    if (router.isReady) {
      // Code using query
      console.log(router.query);
      // this will set the state before component is mounted
      setTitle(router.query.title)
    }
  }, [router.isReady]);

return (
    <>
      <div className="single__page">
        <div className="single__header">
          <h2>{title}</h2>
        </div>
      </div>
     )
}
  • Related