Search code examples
reactjsaxiosuse-effect

React function called multiple time


I'm trying to understand why my function is called 5 times. The function return nothing the first 3 times and then twice with the data. I would like it to run only only once, when the data are ready.

Parent component:

export default function PublicCircles() {

  const [circles, getCircles] = useState('');
  const accessToken = window.localStorage.getItem('accessToken')

  useEffect(() => {
    getPublicCircles();
  }, []);

  const getPublicCircles = () => {
    const headers = {
      'Content-Type': 'application/json',
      'Accept-Language': 'fr',
      'Authorization': `Bearer ${accessToken}`,
    }
     axios.get('https://myurl.com/api/get-public-circles?lang=All', { headers })
      .then((response) => {
          const publicCircles = response.data.data;
          getCircles(publicCircles);
        }) 
      .catch(error => console.log('error', error))
  };

  return (
      <PublicCircle circles={circles} />
  )
}

Child component:

export default function PublicCircle(props) {
  console.log(props.circles)
  return(
    <>
    </>
  )
}

Result: enter image description here

Thank you.


Solution

  • I would like it to run only only once, when the data are ready.

    So you don't want the <PublicCircle> component to be rendered at all until the prop you're sending it has data? In that case you should conditionally render it. Currently you're always rendering it:

    return (
      <PublicCircle circles={circles} />
    );
    

    But you can simply introduce a condition in there. Your default value of circles is an empty string:

    const [circles, getCircles] = useState('');
    

    So check for that in the condition. For example:

    return (
      circles === '' ? null :
      <PublicCircle circles={circles} />
    );
    

    Then the PublicCircles component will render nothing (null) by default, and render a <PublicCircle> element when circles contains data.

    Note that your component may still re-render for any number of reasons. Any state change here or anywhere up the hierarchy can trigger a re-render.