Skip to content

Instantly share code, notes, and snippets.

@guillaumewuip
Created November 12, 2020 06:56
Show Gist options
  • Save guillaumewuip/efdb0e09649739732af86641cf201ef3 to your computer and use it in GitHub Desktop.
Save guillaumewuip/efdb0e09649739732af86641cf201ef3 to your computer and use it in GitHub Desktop.
State and Store in frontend codebases - Redux example - middleware
import { fetchUsers, createUser } from "./fake-fetch";
import {
fetchUsersSucceeded,
fetchUsersFailed,
createUserFailed,
createUserSucceeded
} from "./actionCreators";
export const middleware = ({ dispatch, getState }) => (next) => (action) => {
next(action);
switch (action.type) {
case "FETCH_USERS": {
fetchUsers()
.then((payload) => {
dispatch(fetchUsersSucceeded(payload));
})
.catch(() => {
dispatch(fetchUsersFailed());
});
break;
}
case "CREATE_USER": {
const currentUsers = getState().users;
if (currentUsers.length >= 10) {
dispatch(createUserFailed());
}
createUser()
.then((payload) => {
dispatch(createUserSucceeded(payload));
})
.catch(() => {
dispatch(createUserFailed());
});
break;
}
default: {
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment