Don't Create Contradicting States
Here I forgot to update the error state on success and loading state in error case 💩🧨💣
function Blog() {
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const fetchBlog = () {
setIsLoading(true);
fetch('api')
.then(() => setIsLoading(false));
.catch(() => setIsError(true));
}
}
In the above code it's easy to create a situation where both isLoading
and isError
is true and vice versa.
DO ✅
function Blog() {
const [status, setStatus] = useState<"loading" | "error" | "fulfilled">();
const fetchBlog = () {
status("loading");
fetch('api')
.then(() => setStatus("fulfilled"));
.catch(() => setStatus("error"));
}
}