Created
March 10, 2020 18:19
-
-
Save aaronmaldonado-dev/17ba0facf725bb38ca630147c21ff053 to your computer and use it in GitHub Desktop.
React - basic fetch with debounce component
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, { useState, useEffect } from 'react'; | |
import Lodash from 'lodash'; | |
const DATA_URL = 'https://jsonplaceholder.typicode.com/todos'; | |
function FetchComponent() { | |
const [todoList, setTodoList] = useState([]); | |
const [isLoading, setIsLoading] = useState(false); | |
const fetchData = (id) => { | |
fetch(DATA_URL + '?userId=' + id).then( | |
res => res.json() | |
).then(res => { | |
if(res.length > 0) { | |
const items = res.map((item, index) => { | |
return( | |
<li key={index}>{item.title}</li> | |
); | |
}); | |
setTodoList(items); | |
setIsLoading(false); | |
} | |
}).catch( | |
error => console.log(error) | |
); | |
}; | |
return( | |
<React.Fragment> | |
<select disabled={isLoading} onChange={(ev) => { | |
if(ev.target.value !== 'select') { | |
setIsLoading(true); | |
Lodash.debounce(fetchData, 1000)(ev.target.value); | |
}; | |
}}> | |
<option value="select">Select User ID</option> | |
<option value="1">1</option> | |
<option value="2">2</option> | |
<option value="3">3</option> | |
<option value="4">4</option> | |
<option value="5">5</option> | |
</select> | |
<ul className="results">{todoList}</ul> | |
</React.Fragment> | |
); | |
} | |
export default FetchComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment