Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Last active April 23, 2020 04:23
Show Gist options
  • Save andycarrell/30172c60a253424c936582b5a2f27608 to your computer and use it in GitHub Desktop.
Save andycarrell/30172c60a253424c936582b5a2f27608 to your computer and use it in GitHub Desktop.
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])
}
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])
}
@andycarrell
Copy link
Author

@kirkobyte - definitely ! - Can use Promise.catch too 🙌

@kirkobyte
Copy link

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

@andycarrell
Copy link
Author

@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