Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mobX Auth Store
import mobx, { computed, observable, action } from "mobx"
import store from "store"
import autoStore from "./autoStore"
class Auth {
constructor() {
autoStore("authentication", this)
}
@observable authorization = null
@computed get isAuthenticated() {
return this.authorization ? true : false
}
@action login(body) {
return fetch(__API___, {
method: "POST",
body: JSON.stringify(body)
})
.then((response) => {
return response.json()
})
.then((body) => {
const token = body.token // "abcefghi...
this.setToken(token)
})
}
@action setToken(token) {
this.authorization = `Bearer ${token}`
}
@computed get getToken() {
if (this.authorization) {
return this.authorization.match(/(?:Bearer\s+)?(\w+\.\w+\.\w+)/)[1]
} else {
return null
}
}
@action logout() {
store.clearAll()
}
}
const authStore = window.authStore = new Auth
export default authStore
@patrickmuhi

This comment has been minimized.

Copy link

@patrickmuhi patrickmuhi commented Mar 10, 2019

Nice thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment