clojurecompojureringcompojure-api

Save state on clojure


I'm starting on functional programming now and I'm getting very crazy of working without variables.

Every tutorial that I read says that it isn't cool redefine a variable but I don't know how to solve my actual problem without saving the state on a variable.

For example: I'm working on a API and I want to keep the values throught the requests. Lets say that I have a end-point that add a person, and I have an list of persons, I would like to redefine or alter the value of my persons list adding the new person. How can I do this?

Is there ok to use var-set, alter-var-root or conj!?

(for the api i'm using compojure-api and each person would be a Hash)


Solution

  • Clojure differentiates values from identity. You can use atoms to manage the state in your compojure application.

    (def persons (atom [])) ;; init persons as empty vector
    (swap! persons #(conj % {:name "John Doe"})) ;; append new value
    

    You can find more in docs:

    https://clojure.org/reference/atoms

    https://clojure.org/reference/data_structures

    https://clojuredocs.org/clojure.core/atom