I am new to react redux. I want to add a loading text when the user pressed the search button and dismiss the text when data comes back or the action completed. In a normal async function, I can just toggle the isLoading flag before and after the call back.
However, in my app, I am dispatching an action that returns a 'type' and 'payload' that is a promise. The middleware redux-promise then 'automatically' converts that promise payload and send it to the reducer. In other words, the middleware does the .then action for the promise behind the scene and gives my reducer the correct data.
In this case, I am not sure how I can add a loading text to my view because as soon as I call this.props.getIdByName(this.state.value), I do not know when the data comes back. The logical place for me would be inside the reducer since that is when the data comes back. However, I belive that would be a bad way because reducers should not perform such task?
Inside my component, I have the following function for my submit
handleSubmit(e) {
e.preventDefault();
this.props.getIdByName(this.state.value);
}
Inside my actions/index.js file, I have the following action generator
export function getIdByName(name) {
const FIELD = '/characters'
let encodedName = encodeURIComponent(name.trim());
let searchUrl = ROOT_URL + FIELD + '?ts=' + TS + '&apikey=' + PUBLIC_KEY + '&hash=' + HASH + '&name=' + encodedName;
const request = axios.get(searchUrl)
return {
type: GET_ID_BY_NAME,
payload: request
}
}
Inside my reducers/reducers.jsx
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case GET_ID_BY_NAME:
console.log(action.payload.data.data.results[0].id); <-- here the data comes back correctly because reduer called the promise and gave back the data for me
return {...state, id: action.payload.data.data.results[0].id};
default:
return state;
}
}
And in my main index.js file, I have the store created with the following middleware
const createStoreWithMiddleware = applyMiddleware(
promise,
thunk
)(createStore);