Reputation: 194
I have issue in getting localStorage
value when page loaded
if I refresh the page it is working.
how do i get the localStorage
value when page loaded.
I have two files one is utils.js in this file I have declared a object
export const user = {
id: window.localStorage.userId
};
Another one is userDetails.js in this page i have getting a value on
import {user} from './utils';
componentDidMount=() => {
console.log(user.id);//for the first time its getting null .when i refresh the page value is updated
}
Upvotes: 1
Views: 931
Reputation: 1261
// Use state and props concept for data flow in react
// Util.js
import React, Component from 'react';
class Utils extends Component{
state = {
user: {
id: window.localStorage.userId
}
}
}
export default Utils;
//UserDetails.js
import React, Component from 'react';
import Utils from './Utils';
class UserDetails extends Component{
componentDidMount=() => {
console.log(this.props.user.id);//One time
}
componentWillReceiveProps(newProps){
if(this.props.user !== newProps.user)
console.log(newProps.user); // Each time props changes
}
}
Also, redux can be used for global state management https://redux.js.org/ I hope this helps.
Upvotes: 2