Reputation: 2636
I have a functional component that fetchs some data from an API and show it somewhere in the page, the thing is when an error occurred I want to display a retry button to call the API again. so I did this:
import React, {useEffect, useState} from "react";
import api from "../../../api";
import {useSnackbar} from "notistack";
const ShowPassword = ({uuid}) => {
const [password, setPassword] = useState(null);
const [retry, setRetry] = useState(false);
const {enqueueSnackbar} = useSnackbar();
useEffect(() => {
api.showPassword(uuid)
.then(res => {
setPassword(res.data.password);
})
.catch(err => {
setRetry(true);
enqueueSnackbar('An error occured...', {variant: 'error'});
})
}, [password]);
return (
<div>
{
retry
? <button onClick={() => {
setRetry(false);
setPassword(null);
}} type='button'>Retry</button>
: <span>{password ?? 'Loading...'}</span>
}
</div>
);
};
export default ShowPassword;
but by clicking on the Retry button, It displays Loading...
but the API won't be called again.
Upvotes: 1
Views: 1802
Reputation: 11001
on event of error "password" value not changed. Add some value to password (or some change to indicate in useEffect dependency array).
onClick={() => {
setRetry(false);
setPassword("some value");
}}
Upvotes: 2