user13390075
user13390075

Reputation:

Making sure that useState() hook has been updated by useEffect hook?

I refactored my code to use useEffect hook instead of using class, but I'm getting a memory leak on the refresh of my results. I did use useEffect but I still get a an error message, not sure where I'm making a mistake in my code.

I get the following error:

Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().

      import React, { useEffect, useState} from 'react';
      import { FlatList, View, TouchableHighlight } from 'react-native';
      import { USANews } from '../components/fetchNews';
      import Article from '../components/Article';


      const  homeScreen = ({ handleRefresh, navigation, }) => {
        const [state, setState] = useState({articles: [], refreshing: true});

        useEffect (() => {
          fetchNews();
        }, )

        const fetchNews = () => {
          USANews() .then(articles => {
              setState({ articles, refreshing: false });
            })
            .catch(() => setState({ refreshing: false }));
        };

        handleRefresh = () => {
          setState({ refreshing: true }, () => fetchNews());
        };

          return (
            <View style={{backgroundColor: '#fffafa'}}>
            <FlatList
              data={state.articles}
              keyExtractor={item => item.url}
              refreshing={state.refreshing}
              onRefresh={handleRefresh}
              renderItem ={({item}) => {
                return (
                <TouchableHighlight onPress={() => navigation.navigate('Detail', 
                {title: item.title, description: item.description, urlToImage: item.urlToImage})}
                >
                <Article article={item} />
                </TouchableHighlight>
                );
            }} 
            />
          </View>
          );

      }

      export default homeScreen;

Upvotes: 0

Views: 789

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

Remove the extra parameter from setState({ refreshing: true }, () => fetchNews()) in handleRefresh.

Perhaps also add state to a dependency array in the effect so it only runs when state updates, unless you want the fetch to occur anytime the component renders.

Upvotes: 2

Related Questions