Reputation: 3732
I am trying to use hooks, but am in an infinite loop. The code is below. fetchSomeData and uuid get passed in from the parent component. The data that is fetched is the same every time. Thanks.
import React, { useState } from 'react';
const MyComponent = (props) => {
const [myList, setMyList] = useState([]);
const {fetchSomeData, uuid} = props;
fetchSomeData(uuid)
.then( (response) => {
setMyList(response.payload.data.activities);
})
const renderItem = (item)=>{
return (<div>{item.title}</div>)
}
return (
<div> My COmponent
<div>
{myList.map (renderItem)}
</div>
</div>
)
}
export default MyComponent
Upvotes: 1
Views: 535
Reputation: 21297
Cause you're executing the fetcher function on each render, updating the state and triggering a new render, which fetches data again and so on...
Wrap your imperative code with an useEffect
useEffect(() =>{
fetchSomeData(uuid)
.then( (response) => {
setMyList(response.payload.data.activities);
})
},[uuid])
Now you're only fetching when uuid
changes
Upvotes: 5