Skip to content

Instantly share code, notes, and snippets.

@cayasso
Created August 24, 2017 16:52
Show Gist options
  • Save cayasso/799ad313790e8682ccac780ab4d44239 to your computer and use it in GitHub Desktop.
Save cayasso/799ad313790e8682ccac780ab4d44239 to your computer and use it in GitHub Desktop.
mobx user store example
import { toJS, action, observable, extendObservable } from 'mobx'
import { setToken, unsetToken } from 'lib/api'
import * as storage from 'lib/localstorage'
import * as tokenStorage from 'lib/token'
import { omit } from 'lib/utils'
import sleep from 'lib/sleep'
import * as api from 'user/api'
let store = null
function createStore(state = {}) {
const defaults = {
id: null,
name: '',
email: '',
phone: '',
verifying: false
}
const user = observable({ ...defaults, ...state })
const set = action((data) => {
Object.assign(user, data)
return user
})
const signin = async (email) => {
try {
const { token } = await api.signin(email)
set({ verifying: true })
return await verify({ email, token })
} catch(error) {
return { error }
}
}
const signup = async (data) => {
try {
const { email } = await api.signup(data)
await signin(email)
} catch(error) {
return { error }
}
}
const signout = async (local = false) => {
try {
if (!local) await api.signout()
destroy()
} catch(error) {
return { error }
}
}
const update = async (data) => {
try {
const res = await api.update(data)
set(res, true)
} catch(error) {
return { error }
}
}
const verify = async (creds) => {
try {
console.log('IS USER VERIFYING ====>', user.verifying)
if (!user.verifying) return user
await sleep(2500)
const res = await api.verify(creds)
const { token, user: me } = res
if (token) tokenStorage.set(token)
if (me) set(me)
return me
} catch(error) {
await verify(creds)
}
}
const load = async (ctx) => {
let me = undefined
const token = tokenStorage.get(ctx.req)
if (!token) return me
if (process.browser) me = storage.get('user')
if (!me) me = await api.me(token)
set(me)
setToken(token)
return me
}
const destroy = () => {
if (!process.browser) return
tokenStorage.clear()
storage.clear()
set(defaults)
storage.set('signout', Date.now())
unsetToken()
Router.push('/signin')
}
const cancel = () => {
return set({ verifying: false })
}
const isAuthenticated = async (ctx) => {
if (!user.id) await load(ctx)
return Boolean(user.id)
}
return { user, set, signin, signup, signout, update, verify, load, destroy, cancel, isAuthenticated }
}
export default (state) => {
if (!process.browser || !store) {
store = createStore(state)
}
return store
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment