0

There is an API of friends, and with such code the code endlessly loops, I think this is due to the fact that I do not stop the transmission of responce.result, but I do not know how to fix it

function FriendsAPI(){

const [items, setItems] = useState([1,2,3,4,5,6])
const [loading, setLoading] = useState(false)

useEffect (() =>{
    fetch("https://randomuser.me/api/?results=6&nat=US")
        .then((response) => response.json())
        .then((response) => {
                setItems(response.results)
                setLoading(true)
        })
})
    if(!loading){
        return (
            <div>Loading ...</div>
        )
    }
    else {
        return (
            <div className={classes.WrapperImage}>
                {console.log('render')}
                { items.map((item, index) => (
                    <div className={classes.Pictures} key={index}>
                    <img src={item.picture.medium} alt={item.name.first} className={classes.Img}/>
                    <p>{item.name.first}</p>
                    </div>
                )) }

            </div>
        )
    }
}
4
  • When do you want the fetch to run? Just once when the component mounts? Commented Feb 16, 2021 at 18:13
  • @NicholasTower, Yes, once on page load Commented Feb 16, 2021 at 18:36
  • 1
    Then add an empty dependency array to the effect. useEffect(() => { /* ... */ }, []) Commented Feb 16, 2021 at 18:42
  • @NicholasTower, Thanks a lot, it worked Commented Feb 16, 2021 at 18:47

1 Answer 1

1

in the useEffect add an empty array in the second argument

useEffect (() =>{
    fetch("https://randomuser.me/api/?results=6&nat=US")
        .then((response) => response.json())
        .then((response) => {
                setItems(response.results)
                setLoading(true)
        })
}, [])

That makes it run on componentDidMount

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.