Last active
April 23, 2020 04:23
-
-
Save andycarrell/30172c60a253424c936582b5a2f27608 to your computer and use it in GitHub Desktop.
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
export function useCreateThing() { | |
const dispatch = Redux.useDispatch() | |
return React.useCallback(async (thing) => { | |
dispatch({ type: 'createThing' }) | |
const response = await fetch('/api/thing/create', { body: thing }) | |
if (response.ok) { | |
dispatch({ type: 'createThingSuccess', response }); | |
else { | |
dispatch({ type: 'createThingFailure' }) | |
} | |
}, [dispatch]) | |
} |
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
export function useGetThing() { | |
const dispatch = Redux.useDispatch() | |
const getThing = React.useCallback(async () => { | |
dispatch({ type: 'getThing' }) | |
const response = await fetch('/api/thing') | |
if (response.ok) { | |
dispatch({ type: 'getThingSuccess', response }); | |
else { | |
dispatch({ type: 'getThingFailure' }) | |
} | |
}, [dispatch]) | |
React.useEffect(() => { | |
getThing(); | |
}, [getThing]) | |
} |
I quite like it! Although... Seeing it spelt out like this, makes me more keen for migrating everything I use to redux-toolkit
's createAsyncThunk
https://redux-toolkit.js.org/api/createAsyncThunk
@kirkobyte yeh man I think I would use redux-toolkit
if I was starting a Redux project from scratch - or adding a large new feature to an existing project.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kirkobyte - definitely ! - Can use Promise.catch too 🙌