I have a cookie called '_user_attributes'. The cookie contains a URL encoded string of JSON data. For example,
%7B%22user_id%22%20%3A%20%2212345%22%2C%20%22user_givenName%22%20%3A%20%22First%22%20%7D
which decodes to
{"user_id" : "12345", "user_givenName" : "First" }
Basically, I want to turn the decoded cookie into an object. So I've been doing the following:
var _user_attributes = cookies.get('_user_attributes')
const user_attributes = JSON.parse(_user_attributes)
And that works. The strange thing though, is it only works the first time I load the page. If I refresh the page, I get 'SyntaxError: Unexpected token u in JSON at position 0'.
I am completely confused as to why this is the case. If anyone has any suggestions, I would really appreciate it. The full code of my page is below.
import React, { Component, createRef } from "react";
import { withCookies, Cookies } from "react-cookie";
class App extends Component {
constructor(props) {
super(props)
const { cookies } = props;
var _user_attributes = cookies.get('_user_attributes')
const user_attributes = JSON.parse(_user_attributes)
console.log(_user_attributes)
this.state = {
name: user_attributes.name
}
}
render() {
return (
<p>{this.state.name}</p>
);
}
}
export default withCookies(App);