top of page
Logo der Online Agentur mdwp

Thunk

Thunk in React Js is a middleware that allows you to write action creators that return a function instead of an action. In other words, it allows you to delay the dispatch of an action, or to dispatch only if certain conditions are met. This functionality makes Thunks great for handling complex logic and asynchronous actions like API calls.

The thunk functions can be used to delay the execution of an action or to dispatch an action only if certain conditions are met. The inner function receives the store methods `dispatch` and `getState` as parameters. The delayed actions could be anything from conditionally dispatching actions to making asynchronous API calls.

Here is an example code snippet that demonstrates a Thunk:

```
function fetchPosts(subreddit) {
// Thunk middleware knows how to handle functions.
return function(dispatch, getState) {
// First dispatch: the app state is updated to inform
// that the API call is starting.

dispatch(requestPosts(subreddit));

// The function called by the thunk middleware can return a value,
// that is passed on as the return value of the dispatch method.

return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(
response => response.json(),
// Do not use catch here, because that will also catch
// any errors in the dispatch and resulting render,
// causing an loop of 'Unexpected batch number' errors.
// https://github.com/facebook/react/issues/6895
error => console.log('An error occurred.', error)
)
.then(json =>
// Second dispatch: app state is updated with the results of the API call.

dispatch(receivePosts(subreddit, json))
)
}
}
```

In the above snippet we’re using the fetch API to request the data and dispatching actions when the request starts and finishes. Without a thunk, we’d have no good way to dispatch those actions: the only place we can dispatch is in the event handlers in our components, and we won’t know if the request started or finished until we get a reply from the server.

By using a thunk, we can dispatch the `requestPosts` action to let the state know we’re making a request, then again dispatch `receivePosts` when we get a response. This way the state of our app can react to these changes and render the appropriate UI.

bottom of page