Last active
February 7, 2024 17:14
-
-
Save ismaeldevmw/66a24aa8c981dc57094dffa967ce6090 to your computer and use it in GitHub Desktop.
Custom React Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef, useState } from 'react'; | |
export const useFetch = ( url ) => { | |
const isMounted = useRef(true); | |
const [state, setState] = useState({ data: null, loading: true, error: null }) | |
useEffect(() => { | |
return () => { | |
isMounted.current = false; | |
} | |
}, []) | |
useEffect(() => { | |
fetch( url ) | |
.then( resp => resp.json() ) | |
.then( data => { | |
if ( isMounted.current ) { | |
setState({ | |
loading: false, | |
error: null, | |
data | |
}) | |
} | |
}) | |
.catch( () => { | |
setState({ | |
data: null, | |
loading: false, | |
error: 'Can`t loading the information' | |
}) | |
}) | |
return () => { | |
setState({ data: null, loading: true, error: null }); | |
}; | |
}, [url]) | |
return state; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
function useSearchRule(records, searchPropertyName) { | |
const [query, setQuery] = useState(""); | |
const [filteredRecords, setFilteredRecords] = useState(records); | |
React.useMemo(() => { | |
const result = !query ? records : records.filter(record => ( | |
`${record.searchPropertyName} ` | |
.toLowerCase() | |
.includes(query.toLowerCase()) | |
)); | |
setFilteredRecords(result); | |
}, [records, query]); | |
return { query, setQuery, filteredRecords } | |
} | |
const List = () => { | |
const [records, setRecords] = useState([]) | |
const searchPropertyName = 'name'; | |
const { query, setQuery, filteredRecords } = useSearchRule(records, searchPropertyName); | |
const handleSearch = event => { | |
event.preventDefault(); | |
setQuery(event.target.value); | |
}; | |
return ( | |
<> | |
<label>Search:</label> | |
<input | |
type="search" | |
value={query} | |
onChange={handleSearch} | |
/> | |
<div> | |
{ | |
records.length > 0 | |
? | |
<ul> | |
filteredRecords.map((row) => ( | |
<li key={row.name}>{ row.name row.description}</li> | |
)) | |
</ul> | |
: | |
<p>No hay registros</p> | |
} | |
</div> | |
</> | |
) | |
} | |
export default List; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment