Created
November 12, 2020 06:56
-
-
Save guillaumewuip/efdb0e09649739732af86641cf201ef3 to your computer and use it in GitHub Desktop.
State and Store in frontend codebases - Redux example - middleware
This file contains hidden or 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 { 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