Callbacks are a great tool to achieve SRP. For ex. the following function is responsbile for submitting forms and nothing else.
// SRP
const submitForm = ({apiUrl, payload, onSuccess, onFailure}) => {
fetch(apiUrl, payload)
.then((res) => {
onSucces(res)
})
.catch(err => {
onFailure(err);
})
}
// submit to digio-api - functional programming
const submitFormDigio = ({payload, onSuccess, onFailure}) => {
submitForm({
apiUrl: "https://digio.com/api/submit",
payload,
onSuccess,
onFailure
})
}
// implementation - note that instead of handling notification inside
// submitForm method; we are handling it outside of it. This is one way
// how callbacks helps us in SRP
const onFailure = (err) => setErrors([err])
submitForm({
payload: {},
onSuccess: () => notify("succes", "Form is submitted"),
onFailure
})// without HOC
const greaterThan5Words = word => word.length > 5;
// We may also want to have a dynamic length. To do that we can create an HOC:
const createLengthTest = minLength => word => word.length > minLength
// Now we can re-write our greaterThan5Words
const greaterThan5WordsNew = createLengthTest(5)
// The added advantage of this is that now we can create more variants:
const greaterThan3Words = createLengthTest(6)
const greaterThan20Words = createLengthTest(20) // etc.- Earlier only the
wordargument was dynamic; wheras the minLength was fixed. After introductingHOC; even theminLengthis dynamic. So now we have more flexibility. - This pattern can be very useful for new approach implementation over legacy code.
const arr = [1,2,3,4,5]
const newArr = arr.slice() // clones arrconst arr = [1,2,3,4,5];
const reversedArray = arr.slice().reverse()