Search code examples
javascriptreactjsreact-nativereact-native-flatlist

Class component to functional component is not working as expected


I am implementing infinite scrolling with react-native, when I do a search the result is returned and if the result has many pages on the API, when I scroll the API returns more data .

my implementation works fine on the class component but when I try to convert it to a working component, when I do a search, the data is returned and if I did another search, the previous data from the previous search is still displayed

class component

class Exemple extends React.Component {
  constructor(props) {
    super(props);
    this.searchedText = "";
    this.page = 0;
    this.totalPages = 0;
    this.state = {
      films: [],
      isLoading: false,
    };
  }

  _loadFilms() {
    if (this.searchedText.length > 0) {
      this.setState({ isLoading: true });
      getFilmsWithSearch(this.searchedText, this.page + 1).then((data) => {
        this.page = data.page;
        this.totalPages = data.total_pages;
        this.setState({
          films: [...this.state.films, ...data.results],
          isLoading: false,
        });
      });
    }
  }
  
  _searchTextInputChanged(text) {
    this.searchedText = text;
  }

  _searchFilms() {
    this.page = 0;
    this.totalPages = 0;
    this.setState(
      {
        films: [],
      },
      () => {
        this._loadFilms();
      }
    );
  }

  _displayLoading() {
    if (this.state.isLoading) {
      return (
        <View style={styles.loading_container}>
          <ActivityIndicator size="large" />
        </View>
      );
    }
  }

  render() {
    return (
      <View style={styles.main_container}>
        <TextInput
          style={styles.textinput}
          placeholder="Titre du film"
          onChangeText={(text) => this._searchTextInputChanged(text)}
          onSubmitEditing={() => this._searchFilms()}
        />
        <Button title="Rechercher" onPress={() => this._searchFilms()} />
        <FlatList
          data={this.state.films}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({ item }) => <FilmItem film={item} />}
          onEndReachedThreshold={0.5}
          onEndReached={() => {
            if (this.page < this.totalPages) {
              this._loadFilms();
            }
          }}
        />
        {this._displayLoading()}
      </View>
    );
  }
}

the functional component

const Search = () => {
  const [films, setFilms] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [page, setPage] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [searchedText, setSearchedText] = useState("");

  const _loadFilms = () => {
    if (searchedText.length > 0) {
      setIsLoading(true);
      getFilmsWithSearch(searchedText, page + 1).then((data) => {
        setPage(data.page);
        setTotalPages(data.total_pages);
        setFilms([...films, ...data.results]);
        setIsLoading(false);
      });
    }
  };

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

  const _searchTextInputChanged = (text) => {
    setSearchedText(text);
  };

  const _searchFilms = () => {
    setPage(0);
    setTotalPages(0);
    setFilms([]);
    _loadFilms();
  };

  const _displayLoading = () => {
    if (isLoading) {
      return (
        <View style={styles.loading_container}>
          <ActivityIndicator size="large" />
        </View>
      );
    }
  };

  return (
    <View style={styles.main_container}>
      <TextInput
        style={styles.textinput}
        placeholder="Titre du film"
        onChangeText={(text) => _searchTextInputChanged(text)}
        onSubmitEditing={() => _searchFilms()}
      />
      <Button title="Rechercher" onPress={() => _searchFilms()} />
      <FlatList
        data={films}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => <FilmItem film={item} />}
        onEndReachedThreshold={0.5}
        onEndReached={() => {
          if (page < totalPages) {
            _loadFilms();
          }
        }}
      />
      {_displayLoading()}
    </View>
  );
};

Solution

  • With functional components, you cannot run effects (like getFilmsWithSearch) outside of useEffect.

    From https://reactjs.org/docs/hooks-reference.html#useeffect

    Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI.

    When you are calling _loadFilms from within then onSubmitEditing={() => _searchFilms()} event handler, you are not running inside useEffect, unlike the call to _loadFilms from useEffect that runs with the component mounts (because the second parameter to useEffect is [], it runs once on mount).

    To solve this issue, you would typically have _searchFilms set a state variable (something like reloadRequested, but it does not have to be a boolean, see the article below for a different flavor) and have a second useEffect something like this:

      useEffect(() => {
        if (reloadRequested) {
          _loadFilms();
          setReloadRequested(false);
        }
      }
    , [reloadRequested])
    

    For a more complete example with lots of explanation, try this article https://www.robinwieruch.de/react-hooks-fetch-data.