1

I'm writing a simple SPA game in ClojureScript and I want to save the game state, which is a map, to a cookie and read it back.

I'm successfully saving the cookie, though it turns my map to a string.

When I read it back, I get Error: No protocol method IAssociative.-assoc defined for type string:(then it outputs the map)

What's the simplest and best way to use maps with cookies?

I have tried https://github.com/reagent-project/reagent-utils and https://github.com/Quantisan/cljs-cookies, but I get similar issues.

user619882
  • 350
  • 3
  • 13

1 Answers1

0

I think you're looking for "cljs.core/read-string cljs.core/pr-str" functions. You need to serialize your Clojure objects to string and read it back to store it in a cookie. Functions above will be able to serialize all standard Clojure(Script) data structures for you. And then if you have something custom, this function can come to rescue: https://cljs.github.io/api/cljs.reader/register-tag-parserBANG.

Sergey Shvets
  • 455
  • 1
  • 4
  • 11
  • Thank you for the tips. I will investigate all of your suggestions. Local storage will be a better wat to go. To solve my problem, I removed the functions from my hashmap. I'm concerned about resolving functions in ClojureScript after reading https://stackoverflow.com/questions/12020576/resolve-function-throws-an-error-in-clojurescript-but-not-clojure – user619882 Jul 26 '19 at 16:32
  • Why do you need to resolve a function? If you absolutely need to store function in local storage, you can work around that storing a function key in the map that goes to local storage and use multimethod to dispatch a proper function once you deserialize a map back. – Sergey Shvets Jul 26 '19 at 20:44
  • 2
    The read fn is actually `cljs.reader/read-string`. But, typically you want to persist and read only edn in these situations. For compatibility with Clojure, there is now a `clojure.edn` namespace that ships with ClojureScript, with a `read-string` function in it. – Mike Fikes Jul 26 '19 at 21:16
  • "Why do you need to resolve a function?" I'm writing a game in quil. I was storing some drawing functions to a hashmap because the order to draw them can change based on another value in the hashmap. This worked well until I got to a point where I wanted to persist the game because I didn't want it to reset after every change I made. This is where I hit the problem with saving. I've changed the hashmap to use a keyword instead of the function and I have another hashmap to act as a look-up table to functions I need to draw. Thank you for all the comments. It's helped my understanding a lot. – user619882 Jul 26 '19 at 21:48