Last active
November 12, 2020 07:09
-
-
Save guillaumewuip/be5a0af22bae14c8e86cfd832a6d6e82 to your computer and use it in GitHub Desktop.
State and Store in frontend codebase - State example - service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as User from "./state/user"; | |
import * as State from "./state"; | |
import { store } from "./store"; | |
export const createUserAndSave = ({ | |
firstName, | |
lastName, | |
picture | |
}: { | |
firstName: string; | |
lastName: string; | |
picture?: string; | |
}) => { | |
const currentState = store.read(); | |
if (!State.canCreateUser(currentState)) { | |
return; | |
} | |
const user = User.createNew({ firstName, lastName, picture }); | |
fetch(...) | |
.then(() => { | |
store.apply((currentState) => { | |
if (State.isLoading(currentState) || State.isError(currentState)) { | |
return currentState; | |
} | |
return State.addUser(user)(currentState); | |
})(); | |
}) | |
.catch((error) => { | |
store.apply(() => error)(); | |
}); | |
}; | |
export const init = () => { | |
fetch(...) | |
.then((payload) => { | |
store.apply(() => State.decode(payload))(); | |
console.log({ state: store.read() }); | |
}) | |
.catch((error) => { | |
store.apply(() => error)(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment