Reputation: 187
I need to fetch some data and set the state, but it gives me infinite loop and I don't know how to fix this.
example in my Routes.tsx:
// get all posts
useEffect(() => {
Axios.get('/api/posts', config)
.then(res => setAllPosts(res.data))
.catch(err => console.log(err))
}, [config]);
if I don't put 'config' in dependency, it will show results only on refresh, but then it wont give me infinite loop.
here is my project: https://github.com/marinavrataric/social_network
Upvotes: 0
Views: 320
Reputation: 961
As you are calling your API in useEffect and also updating the state in useEffect too, and useEffect without dependency is called every time the component renders, so here is the loop:
** call the useEffect > call API> updating state using setState> as the state is update, call the useEffect **
So you need to add a dependency for useEffect which is not changed by the setState. And then, whenever the value of the dependentis changed, the API will be called.
BTW, its better not to implement API call in useEffect. Rather You should try using readux and thunk.
Upvotes: 0
Reputation: 1084
Try using useStata[] with useEffect[]
const [data, setData] = useState({ hits: [] });
useEffect(async () => {
const result = await axios.get('/api/posts', config)
.then(res => setAllPosts(res.data))
.catch(err => console.log(err))
setData(result);
}, []);
return (
<ul>
{data.posts.map(item => (
// stuff
))}
</ul>
);
Upvotes: 1