-
-
Notifications
You must be signed in to change notification settings - Fork 114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to fetch multiple URLs (non-constant number) at once? #83
Comments
I'm assuming you're talking about pagination? You could do something like const SomeComp = ({ page, pageLength }) => {
const [list, setList] = useState([])
const { get, loading } = useFetch('url')
const fetchList = async () => {
const theList = await get(`?page=${page}&pageLength=${pageLength}`)
setList(theList)
}
const mounted = useRef(false)
useEffect(() => { // componentDidMount
if (!mounted.current) {
fetchList()
mounted.current = true
}
}, [])
return <div>{list.map(item => <div>{item.text}</div>)}<div>
} Does this make sense? Or are you asking something else? |
Sorry for being unclear. What I actually am trying to do is load multiple URLs at once: const SomeComp = ({urls}) => {
const images = // fetch all the urls
return images.map(/* do something with the results*/)
} However I understand now that I can probably solve it like this: const [results, setResults] = useState([])
const request = useFetch()
async function fetchStuff() {
for (const url of urls) {
const result = await request.get(url)
setResults([...results, result])
}
}
useEffect(() => { fetchStuff() }) |
You can do that, however it's always recommended that you don't have api calls/ |
In my application I am fetching data, not images – that was just for the example. |
You could do something like const Comp = (props) => {
const [imagesData, setImagesData] = useState([])
const [loading, setLoading] = useState(false)
const { get } = useFetch('url')
const getImageData = useCallback(async () => {
setLoading(true)
const imgData = await images.map(async image => await get('/image?id=${image.id}'))
setImagesData(imgData)
setLoading(false)
}, [props.images, imagesData, setImagesData, setLoading])
const mounted = useRef(false)
useEffect(() => {
if (!mounted.current) { // on mount
getImagesData()
}
}, [getImagesData])
return (
<>
{loading && 'Loading...'}
{imagesData.length > 0 && imagesData.map(img => <img src={img.url} />)}
</>
)
} Is this something like what you're looking for? |
@supermihi is your question answered? Gonna close this if it is :) |
@alex-cory thanks for your answer. The above should work (though I'd remove the |
Oh yeah, that makes sense about the |
Ok, thanks a lot! |
Say I need to fetch a list of remote resources, while the length on the list depends on the current props. (How) can I achieve that with use-http? As far as I understand the documentation of react, the number of hooks in a component needs to be constant.
The text was updated successfully, but these errors were encountered: