I use a function component, so i have to use UseState to handle component states. I'm trying to show a spinner when loading data with axios :
import { Spinner } from 'react-bootstrap';
const MandatesPage = props => {
const [mandates, setMandates] = useState([]);
const [loading, setLoading] = useState(false); // to handle spinner hide show
useEffect(() => {
setLoading(true); // here loading is true
console.log(loading)
axios
.get(`${config.api}/mandates`)
.then(response => response.data["hydra:member"],setLoading(false)) // here loading is false
.then(data => setMandates(data))
.catch(error => console.log(error.response));
}, []);
...
if (loading) return
return (
<Spinner animation="border" variant="primary" />
);
}
return (
..... // return the other logic of my app
)
}
my problem is the spinner is not shown and i put console.log(loading) after setLoading(true) but i got false value.
Of course loading
is still false, because the setting is async and will only be true on the next render.
For the next render, the loading spinner will be returned, since loading will be true than. If the axios calls needs short than 16 - 32ms, which is the normal frame for each render in react, the loading spinner will not be shown, because loading will already be set back to false.