Trần Kim Dự
Trần Kim Dự

Reputation: 6102

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

Upvotes: 5

Views: 7393

Answers (2)

francis
francis

Reputation: 4505

This works for me:

const USER = 'user'
const URL = 'http://www.example.com/user'

// here you can also use isServer
if (req) {
    const {data: user} = await Axios.get(URL) 
    localStorage.setItem(USER, JSON.stringify(user))
} else {
    const user = await JSON.parse(localStorage.getItem(USER))
}

Upvotes: 0

dougajmcdonald
dougajmcdonald

Reputation: 20047

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.

Upvotes: 1

Related Questions