React Loading Spinner + Redux?
Solution 1:
First, connect the UploadImage component to the redux store.
Then, create some actions in your actions file:
// You only need to export and call this action from your component:exportconstuploadNewArticleImage = (uploadData) => {
return(dispatch) => {
dispatch(uploadNewArticleImageLoading(true)); // set isLoading = truefetch('uploadData.url', {
method: 'POST',
body: uploadData.data,
etc...
})
.then((response) =>dispatch(uploadNewArticleImageLoading(false))) // response received
.then((response) => response.JSON())
.then((jsonObj) =>dispatch(uploadNewArticleImageSuccess(jsonObj.image))) // success
.catch((error) =>dispatch(uploadNewArticleImageLoading(false)); // error
};
};
constuploadNewArticleImageLoading = (isLoading) => {
return {
type: "UPLOAD_NEW_ARTICLE_IMAGE_LOADING",
payload: {
isLoading: isLoading
}
};
};
constuploadNewArticleImageSuccess = (image) => {
return {
type: "UPLOAD_NEW_ARTICLE_IMAGE_SUCCESS",
payload: {
image: image
}
};
};
Then in your reducer, just handle the actions to update the store.
This way, isLoading
will be set to false whenever we receive a response from the server, or an error occurs during the image upload.
Solution 2:
What I have is that within Redux I have a PageState
object that has various shared properties on it, one of these being isProcessing
. Whenever there is an ajax call, another property called processingCount
is incremented, and then isProcessing
is set to processingCount > 0
;
Whenever an ajax request is then completed or failed, the processingCount
property is decremented.
Your PageState
object can then be used within a Spinner component, can be attached to Buttons to stop disable them while there is processsing going on, or you can show various loading animations throughout the app.
So in your code, I would remove all component state, and move this into your Redux store.
Post a Comment for "React Loading Spinner + Redux?"