17
loading...
This website collects cookies to deliver better user experience
dispatch(action)
. Dispatching an action is the only way to trigger a change in the state.type
. Here is a very basic example.const increaseCount = { type: 'INCREASE_COUNT' }
this.props.dispatch(increaseCount)
function reducer(state = {
count: 0,
}, action) {
switch (action.type) {
case 'INCREASE_COUNT':
return { count: state.count + 1 };
default:
return state;
}
}
increaseCount
as the argument tells the reducer to run the action type of 'INCREASE_COUNT'
. It then returns the new state which is the old state +1.export function fetchMovie(movie) {
return (dispatch) => {
fetch(`${apiURL}${movie}?api_key=${MY_API_KEY}`)
.then((resp) => resp.json())
.then((movie) => dispatch({ type: 'SEARCH_MOVIES', payload: movie}));
};
}
'SEARCH_MOVIES'
action type with the payload of the movie information I got back from my fetch call. That tells the reducer I have set up how to alter the state. In this case I am making the movie in my store be the one that is was just searched.