Skip to content

Instantly share code, notes, and snippets.

@guillaumewuip
Last active November 12, 2020 07:09
Show Gist options
  • Save guillaumewuip/be5a0af22bae14c8e86cfd832a6d6e82 to your computer and use it in GitHub Desktop.
Save guillaumewuip/be5a0af22bae14c8e86cfd832a6d6e82 to your computer and use it in GitHub Desktop.
State and Store in frontend codebase - State example - service
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