Hey folks,
I have this JS that I want to convert into Reason.
const isBrowser = typeof window !== `undefined`
export const setUser = user => (window.localStorage.gatsbyUser = JSON.stringify(user))
const getUser = () =>
window.localStorage.gatsbyUser
? JSON.parse(window.localStorage.gatsbyUser)
: {}
export const isLoggedIn = () => {
if (!isBrowser) return false
const user = getUser()
if (user) return !!user.username
}
export const getCurrentUser = () => isBrowser && getUser()
export const logout = callback => {
if (!isBrowser) return
setUser({})
callback()
}
I can’t seem to get my head around this. This is what I have in Reason:
[@bs.val] external browserEnv: bool = "process.browser";
let isBrowser = browserEnv;
Js.log2("isBrowser: ", isBrowser);
/* This is what is in browser storage:{"email_verified":true,"phone_number_verified":false,"phone_number":"+5555555555","email":"aarmand.inbox@gmail.com","username":"idkjs"} */
let getUser = () => {
let user = Dom.Storage.(localStorage |> getItem("gatsbyUser"));
let result = switch user {
| None => ""
| Some(user) => user
}
Js.log(result);
result;
};
let user = getUser();
// returns
// {"email_verified":true,"phone_number_verified":false,"phone_number":"+5555555555","email":"aarmand.inbox@gmail.com","username":"idkjs"}
Js.log2("USER",user);
Im having a hard time modeling this boolean which is checking if the user is logged in. First we check if we are in the browser and if true, then we check if the user username field exists and if so return true. So this should return true or false
let isLoggedIn = (isBrowser, user) => {
let user = getUser();
switch(isBrowser, user) {
|(false,_) => ()
|(true, user) => {
switch user {
| None => false
| Some(_u) => true
}}
}
};```
Here we want to check if both we are in the browser and if so get back the user.
```re
let getCurrentUser = () => if (isBrowser) {
let user = getUser();
/* return the user */
user;
};
Js.log2("getCurrentUser",getCurrentUser); // returns "getCurrentUser 0"