Skip to content

Instantly share code, notes, and snippets.

@tkssharma
Created September 12, 2019 09:59
Show Gist options
  • Save tkssharma/f678a72e582e3aa35646847619029b7c to your computer and use it in GitHub Desktop.
Save tkssharma/f678a72e582e3aa35646847619029b7c to your computer and use it in GitHub Desktop.
function LocalStorageHook() {
const [count, setCount] = useState(() => {
let value;
try {
value = JSON.parse(
window.locastorage.getItem('count') || '0'
)
} catch (e) {
value = 0;
}
return value;
})
useEffect(() => {
window.locastorage.setItem('count', count);
}, [count])
return (
<span onClick={() => setCount(count + 1)} >Click me {count} </span>
)
}
function FlickerImageHook(searchKey) {
const [images, setImages] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
return async(() => {
setLoading(true);
try {
const res = await axios.get(`http://flicker.api.com/images/${searchKey}`)
setImages(res.data.images);
setLoading(false);
}catch(err){
setError(err)
setLoading(false);
}
})();
},[searchKey])
return [images, loading, error]
}
function GreetingMessageBuilder(searchKey) {
const [message, setMessage] = useState('Hello nice to meet you ');
getMessage = () => {
return 'some random message';
}
useEffect(() => {
const timeout = setInterval(() => {
// generate some tandom message
setMessage(getMessage())
}, 5000)
return clearInterval(timeout)
},[])
return [message, loading ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment