简体   繁体   中英

Query lost on page refresh in NextJS

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>

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>
     )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM