1

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

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.