|
1 |
| -import React, { useState, useEffect } from 'react' |
| 1 | +import React, { useState, useEffect, useCallback, useMemo } from 'react' |
2 | 2 | import PropTypes from 'prop-types'
|
3 | 3 |
|
4 | 4 | import { CardWrap, CardMedia, CardContent, CardEmpty } from './components/Card'
|
@@ -44,29 +44,31 @@ function Microlink (props) {
|
44 | 44 | lazy,
|
45 | 45 | ...restProps
|
46 | 46 | } = props
|
47 |
| - const isLoadingUndefined = loadingProp === undefined |
| 47 | + const isLoadingUndefined = useMemo(() => loadingProp === undefined, [loadingProp]) |
48 | 48 | const [loadingState, setLoading] = useState(
|
49 | 49 | isLoadingUndefined ? true : loadingProp
|
50 | 50 | )
|
51 | 51 | const [cardData, setCardData] = useState({})
|
52 |
| - const apiUrl = createApiUrl(props) |
| 52 | + const apiUrl = useMemo(() => createApiUrl(props), [props]) |
53 | 53 |
|
54 |
| - const isLazyEnabled = isLazySupported && (lazy === true || isObject(lazy)) |
55 |
| - const lazyOptions = isObject(lazy) ? lazy : undefined |
| 54 | + const isLazyEnabled = useMemo(() => isLazySupported && (lazy === true || isObject(lazy)), [lazy]) |
| 55 | + const lazyOptions = useMemo(() => isObject(lazy) ? lazy : undefined, [lazy]) |
56 | 56 | const [hasIntersected, cardRef] = useIntersectionObserver(isLazyEnabled, lazyOptions)
|
57 | 57 |
|
58 |
| - const canFetchData = !isLazyEnabled || (isLazyEnabled && hasIntersected) |
| 58 | + const canFetchData = useMemo(() => !isLazyEnabled || (isLazyEnabled && hasIntersected), [isLazyEnabled, hasIntersected]) |
59 | 59 |
|
60 |
| - const fetchData = () => { |
| 60 | + const fetchData = useCallback(() => { |
61 | 61 | if (canFetchData) {
|
| 62 | + setLoading(true) |
62 | 63 | const fetch = isFunction(setData)
|
63 | 64 | ? Promise.resolve({})
|
64 |
| - : fetchFromApiUrl(apiUrl, props) |
| 65 | + : fetchFromApiUrl(apiUrl, props.apiKey) |
| 66 | + |
65 | 67 | fetch.then(({ data }) => mergeData(data))
|
66 | 68 | }
|
67 |
| - } |
| 69 | + }, [apiUrl, canFetchData, setData, props.apiKey]) |
68 | 70 |
|
69 |
| - const mergeData = fetchData => { |
| 71 | + const mergeData = useCallback(fetchData => { |
70 | 72 | const payload = isFunction(setData)
|
71 | 73 | ? setData(fetchData)
|
72 | 74 | : { ...fetchData, ...setData }
|
@@ -102,7 +104,7 @@ function Microlink (props) {
|
102 | 104 | })
|
103 | 105 |
|
104 | 106 | setLoading(false)
|
105 |
| - } |
| 107 | + }, [setData]) |
106 | 108 |
|
107 | 109 | useEffect(fetchData, [props.url, setData, hasIntersected])
|
108 | 110 |
|
|
0 commit comments