The useEffect won't change the state LIVE when clicked but content does change on reload

Viewed 71

I'm trying to change my page's content when clicking on the link but the thing is it only changes on reload and not directly when clicked.

function Home( { category } ) {
    const [news, setNews] = useState([]);

    useEffect(() => {
        async function newsArticles(){
          const request = await axios.get(category);
          console.log(request.data.articles);
          setNews(request.data.articles);
          return request;
      }
      newsArticles();
    }, [category]);

  return (
    <div className='home'>
      {news.map(ns => (
        <NewsCard className='homeNewsCard' key = {ns.source.id} title = {ns.title} description = {ns.description} image = {ns.urlToImage} link = {ns.url}/>
      ))}
    </div>
  )
}
1 Answers

Since the effect captures the values at the time the component is rendered, any asynchronous code that executed in the effect will also see these values rather than the latest values. Example :

useEffect(()=>{
asyncFunc(props.val)
.then((res)=> setData(res + props.oth))
},[props.val]);

props.oth is used when the promise resolves, but the effecct captures the values of props.val and prips.oth at the time of render , the value of props.oth had changed during the time it took for the promise to reoslve , the code would see the old value

Solution : you can either use reference to store the value of props.oth so your code will always see the latest value or you can add props.oth back to dependency array and return a cleanup function . Example :

useEffect(()=>{
let cncl = false 
asyncFunc(props.val)
.then((res)=>{
if(!cncl)
setData(res + props.oth)})
return ()=> cncl = true}
,[props.val, props.oth])

cncl flag is raised before running the effecct again (when props.val or props.oth have changes comapred with the previous render).

Related