I'm using redux thunk to return an API call on an action:
export const getActiveCampaigns = () => {
return (dispatch, getState) => {
const bearer = 'Bearer ' + getState().login.bearer
return axios.get(API.path + 'campaign/active/?website_id=' + getState().selectedWebsite.selectedWebsite + '&' + API.beaconAPI_client, { headers: { 'Authorization': bearer } })
.then(function (response) {
dispatch({
type: GET_ACTIVE_CAMPAIGNS,
activeCampaigns: response.data.response
})
})
}
}
This works as in it successfully returns a list of campaigns, which I'm rendering into another component using:
class ActiveCampaignsDropdown extends Component {
// usual stuff
componentDidMount(){
this.props.dispatch(getActiveCampaigns())
}
// render function displays campaigns using this.props.activeCampaigns
}
const mapStateToProps = (state) => {
return {
activeCampaigns: state.activeCampaigns.activeCampaigns
}
}
However, note getState.selectedWebsite.selectedWebsite
on the action. This is set from an action elsewhere in the app, where a user chooses a website from a dropdown list. My reducers look like this:
export default function (state = {}, action) {
switch(action.type){
case SET_SELECTED_WEBSITE:
return {
...state,
selectedWebsite: action.websiteId
}
default:
return state;
}
}
export default function (state = {}, action) {
switch(action.type){
case GET_ACTIVE_CAMPAIGNS:
return {
...state,
activeCampaigns: action.activeCampaigns
}
default:
return state;
}
}
My action for setting the selected website:
export const setSelectedWebsite = (websiteId) => {
return {
type: SET_SELECTED_WEBSITE,
websiteId
}
}
This is combined with other reducers like so:
export default combineReducers({
login,
activeWebsites,
activeCampaigns,
selectedWebsite
})
The problem
The contents of the active campaigns dropdown box works fine on page load - and the state tree does update - but it doesn't update when the selected website changes. From what I can see:
- I am dispatching the action correctly
- I am updating state, rather than mutating it
I'm quite disappointed that Redux isn't "just working" in this instance, though it is possible I'm overlooking something silly having had only a few hours sleep! Any help appreciated.