How can I route with array of objects in Next JS?

Viewed 160

I've been struggling to route through pages using next js route query method. I was passing raw array of objects but it became empty in the page. I've been researching and I found a solution to use JSON.stringify(result) and parsing it in the other page with JSON.parse(query.result) and this worked. but when I use this approach on page reload the page crashes and the browser displays the following error.

This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 431

my code in the index.js is

<Link href={{
  pathname: "/TvShows",
  query: {
    result: JSON.stringify(result),
    //result: [result],
    img: img,
    index: index,
  }}}
  //as={"/TvShows"}
>

and the target page is Tvshows.js

first I defined a constants

const [result, setResult] = useState([]);
const [index, setIndex] = useState("");
const [img, setImg] = useState("");
const router = useRouter();
const query = router.query;

then

useEffect (()=>{
  if(router.isReady){
    //console.log(result);
    const res = JSON.parse(query.result);
    setResult(res);
    setIndex(query.index);
    setImg(query.img);
    //console.log(res);
    //router.isReady= false;
  }
},[router.isReady])

the problem is when I stringily and parse these JSON. why is this happening?

and NOTE: in the url section of the page it uses the datas and it is super long.(maybe if that has an effect on it somehow). what is the best way to pass an array to a page?

the local data being passed in JSON.strimgify(result)

const Shows = [
   {
     id: 1,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
   {
     id: 2,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
   {
     id: 3,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
   {
     id: 4,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
] export default Shows;
1 Answers

Interestingly, I couldn't use the word 'code' as a query parameter in my project, so I renamed it to codeTerm. First, I suggest you to stay away some keywords like 'index' or 'code' etc.

In your TvShows component, try to console query object like below

import { withRouter } from 'next/router';

const TvShows = (props) => {
  // the rest of your code
  useEffect(() => {
    console.log(props.router.query);
    if (props.router.query.result)
      console.log(JSON.parse(props.router.query.result));
  }, [props.router]);
  // the rest of your code
}

export default withRouter(TvShows);

You do not need that

const router = useRouter();
const query = router.query;

UPDATE

Can you try to route user using next/router instead of next/link?

import Router from 'next/router';

Router.push(
  {
    pathname: '/TvShows',
    query: {
      result: JSON.stringify(result),
      img: img,
      index: index,
    },
  }
);

This should give you what you want, here's the result

Parsed

Related