score:14
on the constructor
as well as componentwillmount
lifecycle hooks, the server is still rendering the component. on the other hand, localstorage exists as part of the browser's window global, thus you can only use it when the component is rendered. therefore you can only access localstorage on the componentdidmount
lifecycle hook. instead of calling localstorage on the constructor, you can define an empty state, and update the state on componentdidmount
when you can start to call localstorage.
constructor() {
super()
this.state = {
students: [],
student: undefined
token: undefined,
isloggedin: undefined
};
}
componentdidmount() {
this.login();
this.setstate({
student: localstorage.getitem('student') || {},
token: localstorage.getitem('token') || "",
isloggedin: (localstorage.getitem('student' == null)) ? false : true
});
}
score:0
i needed to read a token from localstorage
in nextjs and add it to an axios instance header. it was outside of the component, so i used iife practice to ensure being in client:
(function(){
if(typeof window !== "undefined"){
axiosinstance.defaults.headers.common.authorization = `bearer ${localstorage.getitem('token_key')}`
}
})()
score:0
i have created a function getlocalstorageitem and called this in useeffect with the required key name. after getting the value from localstorage, saved it in a state(i.e currentuser) and used it in initialstate.
const [currentuser, setcurrentuser] = usestate({});
const getlocalstorageitem = (key) => {
return typeof window !== undefined
? window.localstorage.getitem(key)
: null;
};
useeffect(() => {
setcurrentuser({
token: getlocalstorageitem("token"),
refreshtoken: getlocalstorageitem("refreshtoken"),
});
}, []);
const initialstate = {
auth: {
isloggedin: true,
currentuser: currentuser,
},
};
score:1
window object and localstorage won't be available when nextjs is building. so you need to check if the code is running in the browser. if you are running in react hooks you don't need to do this because hooks are always running browser side in react.
just add these two utility functions to your nextjs project.
export const isbrowser = (): boolean => {
return typeof window !== 'undefined'
}
export const nextlocalstorage = (): storage | void => {
if (isbrowser()) {
return window.localstorage
}
}
then you can use it in your code like this
nextlocalstorage()?.setitem('user', json.stringify(user))
score:4
in addition to what @silent said, this works for me
react.useeffect(() => {
if (localstorage) {
const getlocalstate = localstorage.getitem("headless");
console.log("localstate: ", getlocalstate)
}
}, []);
score:10
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);
}
score:17
as everyone already mentioned, nextjs runs both on client and server. on the server, there is no localstorage
, hence the undefined
error.
however, an alternative solution is to check if nextjs is running on the server before accessing the localstorage
. ie
const isserver = typeof window === "undefined";
if(!isserver) {
// access localstorage
...localstorage.get...
}
Source: stackoverflow.com
Related Query
- In reactjs and nextjs constructor getting Reference Error: localstorage is not defined
- reactjs and Facebook API: Getting error 'FB' is not defined no-undef
- How to avoid getting error 'localStorage is not defined' on server in ReactJS isomorphic app?
- ReactJS Library being used in NextJS project says is not a constructor
- Why am I getting "TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function" error when using reactjs hooks?
- Running gunjs with Reactjs and webpack throws Reference Error in console
- ReactJS + Redux, getting error "Failed prop type: Right-hand side of 'instanceof' is not callable"
- _universalCookie.Cookies is not a constructor error in ReactJS
- I wants to build my react app but getting Error TypeError: MiniCssExtractPlugin is not a constructor at module.exports
- Create ReactJS class without constructor and binding error
- React and Redux: Getting is not defined no-undef error
- API call getting CORS error in ReactJS but getting response in node and postman
- Getting Error Like Objects are not valid as a React child In ReactJs
- DirectionsRenderer and DirectionsService @react-google-maps/api not getting rendered and also not throwing error
- ReactJs Checkbox value and date not getting updated in state
- Reactjs and typescript error TS2322: Type is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes
- Spine and Reactjs issues error @esotericsoftware/spine-player' does not contain a default export (imported as 'spine')
- I am trying to start a new react project But I am getting this error and the app is not created. I have installed react globally
- Why my state is not getting set inside class based component and it should work but it is not neither i am getting error
- I am getting an error on login with Auth0 and NextJs
- Not getting data from api into the web page, can anyone help me through this where I am getting an error and what can i do to get data
- cartItems array and localStorage not getting updated
- I am new to nodejs and I'm getting reference error: io is not defined ,I can't figure it out
- "store is not defined" Firebase and ReactJS error
- Getting error "Unhandled Rejection (TypeError): api_call4.json is not a function" even when error is caught in reactjs
- Getting error parsing and displaying JSON object in ReactJS
- Getting an error message while trying to execute Router Component in ReactJS using Jest and Enzyme
- Getting Error "parsererror" "Error: jQuery21106393266040831804_1456914722748 was not called" On Ajax Call Reactjs
- Reactjs and rails implementation error on form 404 not found on the server side
- make two decimal value in reactjs but getting this error TypeError: String(...).toFixed is not a function
More Query from same tag
- Create carousel cards as in fb messenger in react js
- How to display data from json in React
- Within React, why am I not able to use nested arrow functions... Altough normal functions seem to work?
- URL is replaced but component doesn't refresh
- redux form remounted whenever react-intl update action is fired
- How to return a rejected promise from a function that wants to do some async processing first
- d3 svg not rendering on initial component render. React
- Google map Polyline in React
- React.JS: Print Map of object in render
- Why can't browsers use a virtual dom internally as an optimisation?
- How to decode a url in JavaScript or NextJS?
- React - on click text inside component, image appears
- react: functional component that ignores prop changes until callback is triggered
- how to use react custom components?
- Why use useState over this.state?
- React Jest Enzyme - Can not get simple Button Click test to pass
- React leaflet draw - marker icon and drag handler is missing
- React/Typescript : this.setState is not a function
- mongodb data updated, but axios is fetching old data
- React js, Jsfiddle. Can't handle <img>
- Displaying a text data while hovering over the image [React Functional Component]
- ReactJS - Code only runs on first time only
- How can i specific expanded data row in react-table?
- Unwanted Additional Data is coming with Socket.io and Jquery
- React.js - default prop is not used with `null` is passed
- display button upon typing input react
- Unable to deploy application on heroku
- JSX not producing expected output with SPAN nested in A
- TypeError: headers[key].trim is not a function
- Import bootstrap CSS in React failed to compile