Reputation: 203
I'm using react native and axios for calling HTTP requests. What I do for displaying spinner is set isLoading in my component state to true before calling my HTTP requests and after fetching data or error occured set it to false. Then I have a spinner component and showing it based on the isLoading value...
Is it possible to have global spinner that does not require to the above in all of my components?
I think Interceptors in axios can help with this?
Upvotes: 4
Views: 1763
Reputation: 1180
There are packages available for that but I'd recommend design in your own way.Below are the steps. Make a separate component in your project and named it "Loader.js"
import React, { Component } from "react";
import { View } from "react-native";
import Spinner from "react-native-spinkit";
export default Loader = ({ isVisible }) => (
<View
style={{
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: "center",
justifyContent: "center",
backgroundColor: nullBackground ? null : "rgba(0, 0, 0, 0.7)",
zIndex: addZindex ? 2 : null
}}
>
<Spinner isVisible={isVisible} size={20} type={"Circle"} color={"white"} />
</View>
);
I've used Spinner as indication.You can use activityIndicator instead. Now in app.js(or your root class of app)import it and use it in render
import Loader from "../Loader";
render() {
const { HUD } = this.props;
return(
<Loader isVisible={HUD} />
)}
This HUD is a state maintained in store
export const showHUD = () => {
return { type: "SHOW_HUD" };
};
export const hideHUD = () => {
return { type: "HIDE_HUD" };
};
export const sendPlayerID = id => async dispatch => {
let payload = { user: { one_signal_id: id } };
dispatch(showHUD());
const { data } = await axios.put(api.profile(), payload);
dispatch(hideHUD());
};
So the flow would be like this.Each time you are going to send request.You will dispatch showHUD which will make HUD state in store= true.Then render function of App.js will run again.And showing HUD above your any screen because it is absolute & has higher index.Similarly once you have received data.Then dispatch hideHUD.Which will then hide the loader.You can show & hide HUD from any point in app.Because it is an action which then will update state.
Upvotes: 1