Reputation: 381
I have the following component that makes a call to an API (googleSearch()), and using the results passes them to the child component.
The problem is that when the props.date is updated externally, the console.log(search_date)
prints the new date however the useEffect
just re-uses the old result, and does not make a new API call.
export default function News(props) {
var searchDate = moment(props.date, "YYYY-MM-DD HH:mm:ss");
var string_date = searchDate.format("MMMM+DD+YYYY");
var nice_date = searchDate.format("MMMM DD YYYY");
const [search_results, updateSearch] = React.useState([]);
console.log(search_date)
React.useEffect(() => {
googleSearch(string_date).then((response) => {
if (response === "undefined" || response === undefined) {
updateSearch([])
} else {
updateSearch(response.data.items)
}
});
},[]);
return (
<React.Fragment>
<Button>News For {nice_date}</Button>
<GoogleTable data={search_results} date={props.date} />
</React.Fragment>
);
Upvotes: 0
Views: 40
Reputation: 9571
You need to pass string_date
into the dependency array on the effect.
React.useEffect(() => {
...
}, [string_date])
That makes the effect run when the value of string_date
changes, including on mount, and it runs with that new value of string_date
An empty dep array will only run on mount, and not providing an array at all will run the effect on every render
Upvotes: 3