Losing query string by refreshing page in Nextjs using express

Viewed 452

I have a problem with nextjs and none of solutions helped me!!! I, m trying to have a dynamic route in my SSR project, everything is working well in localhost, but when I try to upload it to the server or my IIS problem shows on : The problem is this that everything works fine at first render from the server and after refreshing the page I lose my query string and Undefined error happens. Here are my codes:

Server.js:

const express = require("express");
const next = require("next");
const port = process.env.PORT || 3003;

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get("/", (req, res) => {
    return app.render(req, res, "/index");
  });

  server.get("/test?org&des&roomRules&departing&returning", (req, res) => {
    return app.render(req, res, "/test" , {
      org: req.query.org ,
      des: req.query.des,
      roomRules:req.query.roomRules,
      departing: req.query.departing,
      returning: req.query.returning,
    });
  });

  server.get("*", (req, res) => {
    return handle(req, res);
  });
  server.listen(port, err => {
    if (err) throw err;
    console.log(`READY ON  http://localhost:${port}`);
  });
});

Parent Component:

const RoundButton = props => {
  const { searchParams , name} = props;
  const URL2 = `/test?org=${searchParams.org}&des=${searchParams.des}&roomRules=${searchParams.roomRules}&departing=${searchParams.orgDate}&returning=${searchParams.desDate}`;
  return (
    <Link  href={URL2} as={URL2}>
      Test
    </Link>
  );
};

Test Componet :

function Test(props) {
  return (
    <div>
      <h1>Test</h1>
      <h2>roomrules :{props.queryStrings}</h2>
    </div>
  )
}

Test.getInitialProps =  ({query}) => {
  const queryStrings =  query;
  return {
     queryStrings: queryStrings 
  };    
};

export default Test

As you can see I used getInitialProps and it only works on first render.

And finally my scripts in package.json:

"scripts": {
  "dev": "node server.js",
  "build": "next build && next export",
  "start": " node server.js"
},

To publish I write "npm run build" in cmd. Any solution?

1 Answers

As you are using the next js you can use the following approach to make the URL parameter persistent in refresh: Assume you had a component named TestComponent:

TestComponent.getInitialProps = async (context: any) => {
  const { oid } = context.query;
  return { id: oid };
};

The oid is the parameter that you want to be persistent after page refresh and not be undefined.

export default function TestComponent(props: any) {
     props.id
}

This is the approach that you are using in the source code, the other approach is as follow:

export default function TestComponent(props: any){
  const router = useRouter();
  const { oid } = router.query;
}

now you have access to the oid and for the useEffect function use the following approach:

export default function TestComponent(props: any){
      const router = useRouter();
      const { oid } = router.query;
      useEffect(function(){
       }, [oid])
    }

with this setup, your code should also work on Refresh, consider if you have multiple calls to fetch data from the server you have to check that multiple requests precisely.

Related