Reputation: 105
I call a JSON file with Axios and I do not understand why podcastClick function is automatically executed (and does not work if I click), and executed twice?
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [podcasts, setPodcasts] = useState([]);
useEffect(() => {
const fetchData = async () => {
let urlApi = '';
if (process.env.NODE_ENV === 'development') {
urlApi = 'http://localhost:3000';
} else {
urlApi = 'TODO';
}
const response = await axios.get(`${urlApi}/podcasts/podcasts.json`);
setPodcasts(response.data);
}
fetchData();
}, []);
function podcastClick(data) {
console.log('Le lien a été cliqué : ' + data);
}
return (
<ul>
{podcasts.map((repo,key) =>
<li key={key} onClick={podcastClick(repo.title)}>{repo.title}</li>
)}
</ul>
);
}
export default App;
Upvotes: 0
Views: 662
Reputation: 281626
While assigning the eventhandler
to onClick
, you are invoking the function instead of passing a reference so everytime the component is rendered the function will get invoked automatically.
You can use arrow function to pass in the custom variable to invoked function and use it like below
<li key={key} onClick={() => podcastClick(repo.title)}>{repo.title}</li>
Upvotes: 2