How do i access the data from a token stored in local storage in react

Viewed 1422

I am using MERN stack and Redux. I have a jwtToken saved to local storage when a user logs in. I have a form for submitting information and one of the properties on that form is author which i want to automatically populate with the id of the user who is logged in. To access this form you need to be logged so the information will always be there. Anyone have any idea how i do this? This is what i have just now but it doesn't work. As well as being saved in local storage it is accessible via the global state but again i don't really know how to access this or which option is better to use.

class AddSubject extends Component {
  constructor() {
    super();
    const user = localStorage.getItem("jwtToken");
    this.state = {
      title: "",
      summary: "",
      description: "",
      author: user._id,
      errors: {},
    };
  }
4 Answers

You need to decode the token and get user_id. Try this:

const jwt_decode = require('jwt-decode');
class AddSubject extends Component {
  constructor() {
    super();
    const token = localStorage.getItem("jwtToken");
    const data = jwt_decode(token);
    this.state = {
      title: "",
      summary: "",
      description: "",
      author: data.user._id,
      errors: {},
    };
  }

I am not sure, but it can help you:

class AddSubject extends Component {
  constructor() {
    super();
    this.state = {
      title: "",
      summary: "",
      description: "",
      author: localStorage.getItem("jwtToken")._id || '',
      errors: {},
    };
  }

Since you are using redux for data management, it is better to store the decoded token details from localStorage to redux store during app init. That way, user info is available globally and you dont need to access the localstorage ever time the component mounts, and other components that requires to show user info can also share it from global store.

In your componentDidMount life cycle:

window.localStorage.getItem(token)
Related