Consider the following code:
import React from 'react'; import Card from './components/Card'; import './App.css'; import Buttongrp from './components/Buttongrp'; import { useEffect, useState } from 'react'; function App() { useEffect(() => { getData(); }, []) const getData = () => { fetch('https://reqres.in/api/users') .then(response => response.json()) .then(data => { setDataArray(data) }) } const getSingleData = () => { fetch(`https://reqres.in/api/users/${Math.floor(Math.random() * 10) + 1}`) .then(response => response.json()) .then(datajson => { setEmail(datajson.data.email); setFirstName(datajson.data.first_name); setLastName(datajson.data.last_name) }) } const [cardImgUrl, setCardImgUrl] = useState("https://i.pinimg.com/564x/a0/d5/c9/a0d5c9af2eee2970a6eea591fade8271.jpg") const [firstName, setFirstName] = useState("") const [lastName, setLastName] = useState("") const [email, setEmail] = useState("") const [dataArray, setDataArray] = useState({}) return ( <> <div className="container d-flex my-3"> <div className="display-4 mx-auto d-inline">CV Screener</div> </div> <div className="container-fluid my-3"> <Card cardImgUrl={cardImgUrl} firstName={firstName} lastName={lastName} email={email} /> </div> <div className="container d-flex justify-content-center flex-md-row flex-lg-row flex-sm-column flex-xs-column" > <div className="d-inline" > { dataArray?.data && dataArray.data.map((e) => { return <Buttongrp id={e.id} getSingleData={getSingleData} /> }) } </div> </div> </> ); } export default App;
and also the component:
import React from 'react' import { FaUserAlt } from 'react-icons/fa'; function Buttongrp(props) { return ( <> <button type="button" className="btn btn-light btn-lg mx-2 my-2" onClick={props.getSingleData()} > <FaUserAlt /> Fetched User {props.id} </button> </> ) } export default Buttongrp
The function ‘getSingleData’ is being called infinitely, till my pc runs out of memory. I have set it to being called only upon clicking the button and yet its still being called even though I didnt click the button even once. I am unable to figure out why this behavior is happening
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try this:
onClick={() => props.getSingleData()}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0