I am using react and redux with Promise/thunk as middleware. It works great.
There is sne thing I can't figure out. The following works:
I dispatch an action from my component:
this.props.dispatch(addTag({ name: name, photoId: this.props.photoId}))
My action executes an ajax wrapped in thunk and returns a promise:
export function addTag(payload) {
var url = "/api/photos/".concat(payload.photoId, "/addtag?name=" ,payload.name)
return function(dispatch) {
var request = new Request(url, {headers: headers});
fetch(request)
.then((response) => {
dispatch({type: "ADD_TAG", payload: response.json()})
})
.catch((err) => {
dispatch({type: "ADD_TAG", payload: err})
})
}
}
and the reducer picks it up:
case 'ADD_TAG_FULFILLED': {
newState = state
.set('tags', action.payload.tags)
.set('inputValue', '')
return newState
}
Now, what if I want to pass the payload, which is passed to the action, through to the reducer? (in order to get i into state and back to the component... I can only do this, by mingling the Thunk and kind of "breaking" the promise middleware functionality....Is this the best solution?
export function addTag(payload) {
var url = "/api/photos/".concat(payload.photoId, "/addtag?name=" ,payload.name)
return function(dispatch) {
var request = new Request(url, {headers: headers});
fetch(request)
.then((response) => {
return (response.json())
})
.then((json) => {
dispatch({type: "ADD_TAG", payload: {suggestions: json, pl: payload})
})
.catch((err) => {
dispatch({type: "ADD_TAG", payload: err})
})
}
}
Solution is:
export function tagInput(tagInput) {
var url = '/api/photos/get_tag_list?term='.concat(tagInput);
return function (dispatch) {
var request = new Request(url, { headers: headers, method: 'GET' });
fetch(request)
.then(response => {
dispatch({ type: 'TAG_INPUT', payload: response.json() });
})
.catch((err) => {
dispatch({ type: 'TAG_INPUT_ERROR', payload: err });
})
.then(() => {
dispatch({ type: 'TAG_INPUT_VALUE', payload: tagInput });
});
};
}