-1

I am trying to set the value of a cookie from data that I have loaded from a json (will come from axios call in the functional app). Here is a link to the codesandbox. If you want to look through the code here is the data.JSON:

{
"accounts": [
{
  "accountid": "stuff",
  "accountName": "moreStuff",
  "anotherField": "someMoreStuff"
},
{
  "accountid": "stuff",
  "accountName": "moreStuff",
  "anotherField": "someMoreStuff"
}]}

Here is my index.js

const rootElement = document.getElementById("root");
ReactDOM.render(
 <React.StrictMode>
   <CookiesProvider>
     <App />
   </CookiesProvider>
 </React.StrictMode>,
 rootElement
);

Here is how I am using cookies in my app.js

         static propTypes = {
        cookies: instanceOf(Cookies).isRequired
      };
      constructor(props) {
        super(props);
        const { cookies } = props;
        this.state = {
          AccountData: cookies.get("AccountData") || ["Option1","Option2","Option3","Option4"]
        };
      }

      componentDidMount = () => {
        const { cookies } = this.props;
        console.log(AccountData);
        let tempAccountData = AccountData;
        cookies.set("AccountData", tempAccountData);
        console.log(cookies.getAll());
      };

      getCookieValueLater = () => {
        const { cookies } = this.props;
        console.log(cookies.getAll());
      };
      render() {
        return (
          <div className="App">
            <h1>Hello CodeSandbox</h1>
            <h2>Start editing to see some magic happen!</h2>
            <button onClick={() => this.getCookieValueLater()}>
              getCookieValueLater
            </button>
          </div>
        );
      }
    }

    export default withCookies(App);

I believe that it is an issue with inserting an object with fields. Here is a link to the codesandbox again. Thanks for any help and feel free to let me know if im doing something stupid.

Say u
  • 129
  • 11

2 Answers2

2

For anyone that has looked through my code and you still cant set the cookie, make sure that the code you are setting is a max of 4kb. The maximum size of a cookie is 4kb and react-cookies prevents you from setting the cookie if the data you are passing is too large. Hope this helps someone.

Say u
  • 129
  • 11
0

You did it correctly. I ran this locally with no issue. It appears that codesandbox is not allowing the storage of your cookies within the sandbox (possibly security reasons).

reynoldsbj
  • 329
  • 1
  • 8