How can i show a loading animation while ajax is loading? so far i could make an animation using react loaidng webpack aind now i want it to show when ajax is loading is it possible??
class PersonList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<tbody style={{"background":"#c3e6cb"}}>
{
this.state.persons
.map(person =>
<tr key={person.id}>
<td>{person.name}</td>
</tr>
)
}
</tbody>
)
}
}
function Preloader(){
const [data, setData] = useState([]);
const [done, setDone] = useState(undefined);
useEffect(() => {
setTimeout(() => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
setData(json);
setDone(true);
});
}, 1000);
})
First set in your state when its loading
componentDidMount() {
this.setState({isLoading: true});
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
.finally(() => {
this.setState({isLoading: true});
})
}
Then in your render function take that into consideration
render() {
return (
<>
{this.state.isLoading
? <div>**Some loading animation**</div>
: <tbody style={{"background":"#c3e6cb"}}>
{
this.state.persons
.map(person =>
<tr key={person.id}>
<td>{person.name}</td>
</tr>
)
}
</tbody>
}
</>
)
}