Skip to content

Commit

Permalink
#27 Custom useImageOnload
Browse files Browse the repository at this point in the history
  • Loading branch information
fdhhhdjd committed Sep 18, 2023
1 parent 4d19093 commit 983ff9c
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/custom_hooks/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
//* LIBRARY
import React from 'react';
import Learn_1 from './learn_1/useFetch';
import Learn_2 from './learn_2/useDebounce';

// import Learn_1 from './learn_1/useFetch';
// import Learn_2 from './learn_2/useDebounce';
// import Learn_3 from './learn_3/useImageOnload';

const CustomHook = () => {
return (
<>
{/* <Learn_1 /> */}
{/* <Learn_2 /> */}
{/* <Learn_3 /> */}
</>
);
};
Expand Down
21 changes: 21 additions & 0 deletions src/custom_hooks/learn_3/useImageOnload/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import useImageOnload from './useImageOnload';

function Learn_3() {
const imageUrl =
'https://res.cloudinary.com/ecommerce2021/image/upload/v1663398918/profile-forme/avatar_ws0jhh.png';
const [loaded, error] = useImageOnload(imageUrl);

return (
<div>
{error && <p>{error}</p>}
{loaded ? (
<img src={imageUrl} alt="Loaded Image" style={{ width: '50%' }} />
) : (
<p>Loading...</p>
)}
</div>
);
}

export default Learn_3;
36 changes: 36 additions & 0 deletions src/custom_hooks/learn_3/useImageOnload/useImageOnload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useState, useEffect } from 'react';

function useImageOnload(src) {
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(null);

useEffect(() => {
const image = new Image();

const handleLoad = () => {
setLoaded(true);
setError(null);
};

const handleError = () => {
setLoaded(false);
setError('Error loading image');
};

image.addEventListener('load', handleLoad);
image.addEventListener('error', handleError);

// Bắt đầu tải hình ảnh khi src thay đổi
image.src = src;

// Hủy bỏ event listeners khi component bị unmount
return () => {
image.removeEventListener('load', handleLoad);
image.removeEventListener('error', handleError);
};
}, [src]);

return [loaded, error];
}

export default useImageOnload;

0 comments on commit 983ff9c

Please sign in to comment.