Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In reactjs and nextjs constructor getting Reference Error: localstorage is not defined

i make system jsonwebtoken in reactjs and use nextjs. i find problem when i run the code in browser that is localStorage is not defined.

this is my code in file AuthStudentContext.js

import React from 'react'
import axios from 'axios'

const axiosReq = axios.create()
const AuthStudentContext = React.createContext()

export class AuthStudentContextProvider extends React.Component {

    constructor() {
        super()
        this.state = {
            students: [],
            student: localStorage.getItem('student') || {},
            token: localStorage.getItem('token') || "",
            isLoggedIn: (localStorage.getItem('student' == null)) ? false : true
        }
    }

    login = (credentials) => {
        return axiosReq.post("http://localhost:4000/api/login", credentials)
            .then(response => {
                const { token } = response.data
                localStorage.setItem("token", token)

                this.setState({
                    token,
                    isLoggedIn: true
                })

                return console.log(response)
            })
    }

and show error localStorage is not defined

like image 722
Toni Suwendi Avatar asked Dec 31 '19 06:12

Toni Suwendi


People also ask

How do you fix localStorage is not defined in next js?

To solve the "ReferenceError: localStorage is not defined" error, make sure to only use the localStorage object in the browser. The localStorage property is defined on the window object and is not available on the server - e.g. in Node. js or when using server side rendering with Next. js.

Can I use localStorage in Nextjs?

This is because localStorage is not defined on the window object, and Next. js performs a server render before the client render. Therefore, you'll not be able to access localStorage until the page has loaded on the client and the window object has been defined.

Can I access localStorage in getServerSideProps?

As you mentioned localStorage and sessionStorage are not available on the server. You could use cookie and access them inside getServerSideProps via req. cookies .


1 Answers

I never touched nextjs but i guess its equivalent to Nuxt.js. So it does server side rendering while you try to access localstorage on the client side.

You will need to use componentDidMount() for this. Here an example

componentDidMount(){
   localStorage.setItem('myCat', 'Tom');
   alert("Tom is in the localStorage");
}

EDIT:

Otherwise you could try with process.browser

if (process.browser) {
   localStorage.setItem("token", token);
}
like image 166
Ifaruki Avatar answered Oct 17 '22 02:10

Ifaruki