(text)
| 93 | // This function does not need to be pure, and thus allowed |
| 94 | // to have side effects, including executing asynchronous API calls. |
| 95 | export function createTopic(text) { |
| 96 | return (dispatch, getState) => { |
| 97 | // If the text box is empty |
| 98 | if (text.trim().length <= 0) return; |
| 99 | |
| 100 | const id = md5.hash(text); |
| 101 | // Redux thunk's middleware receives the store methods `dispatch` |
| 102 | // and `getState` as parameters |
| 103 | const { topic } = getState(); |
| 104 | const data = { |
| 105 | id, |
| 106 | count: 1, |
| 107 | text |
| 108 | }; |
| 109 | |
| 110 | // Conditional dispatch |
| 111 | // If the topic already exists, make sure we emit a dispatch event |
| 112 | if (topic.topics.filter(topic => topic.id === id).length > 0) { |
| 113 | // Currently there is no reducer that changes state for this |
| 114 | // For production you would ideally have a message reducer that |
| 115 | // notifies the user of a duplicate topic |
| 116 | return dispatch(createTopicDuplicate()); |
| 117 | } |
| 118 | |
| 119 | // First dispatch an optimistic update |
| 120 | dispatch(createTopicRequest(data)); |
| 121 | |
| 122 | return makeTopicRequest('post', data) |
| 123 | .then(res => { |
| 124 | if (res.ok) { |
| 125 | // We can actually dispatch a CREATE_TOPIC_SUCCESS |
| 126 | // on success, but I've opted to leave that out |
| 127 | // since we already did an optimistic update |
| 128 | // We could return res.json(); |
| 129 | return dispatch(createTopicSuccess()); |
| 130 | } else { |
| 131 | throw new Error("Oops! Something went wrong and we couldn't create your topic"); |
| 132 | } |
| 133 | }) |
| 134 | .catch(ex => { |
| 135 | return dispatch(createTopicFailure({ id, ex: ex.message })); |
| 136 | }); |
| 137 | }; |
| 138 | } |
| 139 | |
| 140 | export function incrementCount(id, index) { |
| 141 | return dispatch => { |
no test coverage detected