Académique Documents
Professionnel Documents
Culture Documents
Also make sure you import connect from the 'react-redux' package.
Now we just have to do in /actions our actions and create them in a way that are “Action Creators” it means to
dothem as functions like this:
ok like this:
And import the action in the container onyou are going to use it.
render() {
return (
<Provider store={store}>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
</Provider>
);
}
In App.js import the Provider component from the react-redux package and the store from store.js.
Run your app like normally, you should see the standard 'Welcome to React' page. Check in the Redux tools and
make sure there's a property 'albums' in your state which contains an empty array.
And Now,
We just have to create dispatch that action to the reducer so we can create a new State.
this.props.dispatch(actionCreator())
But it can be done in a way its more efficient that is by using bind action creators.
this.props.dispatch(actionCreator_1());
We will use:
this.props.actionCreator_1();
Be aware that at this point, because we are binding the action to connect, this.props.dispatch() in no
longer available.
Now we just have to import the const that creates the type of the actionCreator and put it in the reducer,
using a swith to go ove the places and changing the state according to the payload we got.
Always remember, an action have an effect if there is a reducer listening to that action.
return {
stocks: state.stocksReducer
We have to optiosn:
1. We copy the code in every component we want to use the data. (Bad idea cause then we are
duplicating the code.
2. We pass that fetching code into a fucntion actionCreator to put it in the store, (Thats a better
Idea)
The problem is that now we can not access to dispatch() to dispatch that data into the store
from the promise of the fetch data, because of using the bind action creator →
mapDispatchToProps.
To solve this problem we have Redux-thunk, which works like a middleware, allowing the
dispatch method to happen inside a function.
First:
Notice that: intalling the middleware does change how actions work, so the
actionCreators still working the same, we only gain the hability to dispatch a
function as well thanks to redux-thunk midddleware. The rest continues
working the same.
The function to dispatch will receive the dispatcher function like this: