Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS: Get data from local storage in getInitialProps method

I try to migrate my project to Next.js framework for having SSR (Server side rendering) feature. Here is my simple page:

class Example extends React.Component {
  static getInitialProps() {
    // api getting data. Need authentication data under local storage
  }
  render() {
    return <div>{this.props.data}</div>;
  }
}

The problem I met is: I want my data is from getInitialProps first (that is the purpose of SSR). But when sending, I need a information about user for backend API. But at this function, rendering is happened on server so I cannot get data from local storage. How can you solve this problem.

Thanks

like image 608
Trần Kim Dự Avatar asked Nov 07 '22 14:11

Trần Kim Dự


1 Answers

You can put the call to localStorage into a react component lifecycle method such as componentDidMount and then setState() with the result.

It's not great, but will work.

Note that this would obviously not use SSR.

like image 121
dougajmcdonald Avatar answered Nov 15 '22 04:11

dougajmcdonald