Dino Geek, try to help you

How to use Redux Thunk?


Redux Thunk is a middleware that allows your actions to return functions. It becomes very useful when you want to perform asynchronous operations with Redux.

Here is a simple guide on how to use Redux Thunk:

1. Install Redux Thunk:
To use Redux Thunk, you first have to install it. You can add it to your project using npm:

```
npm install redux-thunk
```

1. Apply Middleware:
After installation, you’ll need to apply the Redux Thunk middleware:

```
import { createStore, applyMiddleware } from ‘redux’;
import thunk from ‘redux-thunk’;
import rootReducer from ‘./reducers’;

const store = createStore( rootReducer, applyMiddleware(thunk)
);
```

This will enable your application to use Thunk.

1. Creating Thunk Actions:
Now in your action creators, instead of returning an action object directly, you can return a function:

```
export function fetchPosts() { return function(dispatch) { return fetch(‘/api/posts’) .then(res => res.json()) .then(posts => dispatch({ type: “FETCH_POSTS”, payload: posts }) ); };
}
```

Above, ‘dispatch’ is the method we can execute to dispatch actions to Redux. The fetch is asynchronous so we are returning a function that dispatches an action when the response comes back.

1. Dispatching Thunk Actions:
You can now dispatch a thunk action in the same way as normal actions. You can use the `mapDispatchToProps` in `react-redux`‘s `connect` function:

```
import { fetchPosts } from “./actions”;

function mapStateToProps(state) { return { posts: state.posts };
}

const mapDispatchToProps = { fetchPosts: fetchPosts
};

export default connect( mapStateToProps, mapDispatchToProps
)(PostsComponent);
```

In the connected component, `this.props.fetchPosts` will dispatch the thunk action and start fetching the posts. When the posts are fetched, it will dispatch another action with the posts to update the state.

By introducing Thunk, your Redux actions, instead of merely returning action objects directly, are now allowed to return functions, promise functions or async/await functions to perform asynchronous operations.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use