Search code examples
reactjsnext.jsgetserversideprops

pass object from one page to another page NextJS


I want to pass nested object data from one page to the next page. I want to pass the object. We can not use localStorage or sessionStorage because we have to consume object values from getServerSideProps. We do not use here router query as it passes a query that takes key pair value.


Solution

  • Thanks, @Smaiil I am coming up with a solution. We can not send an object through localStorage. We can work through it via query.

    const queryData = {
      key1: 'value1',
      key2: 'value2',
      key3: 'value3',
    }
    
    router.push({
        pathname: 'pathname',
        query: queryData,
      },
      'pathname' // use this to clear query strings like key value from URL
    );
    

    This way we can send query data and do getServerSideProps implementation to the respective page. refer below

    export async function getServerSideProps({ query }) {

     try {
        const response = await wretch(
          `API URL`
        )
          .post(query)
          .json();
        const scheme = response.data;
        return {
          props: { scheme },
        };
      } catch (error) {
        return {
          props: {},
        };
      }
    }