Skip to content
Advertisement

Why my data is flickering between previous and new when state is updated in ReactJS?

I’m working on a SPA with data fetch from the Star Wars API. In the characters tab of the project, the idea is to display the characters per page and you can click next or prev to go to page 2, 3, etc. That works, but! the character names flicker everytime the page changes, it doesn’t happen after the first click, but if you keep going, it happens more and more.

I tried to fixed it by cleaning the state before rendering again, but it’s not working. The data is first fetched after the component mounts, then when the btn is clicked I use the componentwillupdate function to update the character component.

You can see the component here: https://github.com/jesusrmz19/Star-Wars-App/blob/master/src/components/Characters.js

And the live project, here: https://starwarsspa.netlify.app/#/Characters

Advertisement

Answer

see if this solves your problem

class Characters  extends React.Component { 
constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      webPage: "https://swapi.dev/api/people/?page=",
      pageNumber: 1,
      characters: [],
    };
    this.fetchHero = this.fetchHero.bind(this);
  }



async fetchHero(nextOrPrev) {
    //nextOrPrev values-> 0: initial 1: next page -1:prev page
    let pageNum = this.state.pageNumber + nextOrPrev;
    try {
      const response = await fetch(this.state.webPage + pageNum);
      const data = await response.json();
      const characters = data.results;
      this.setState({
        pageNumber: pageNum,
        characters,
        isLoaded: true,
      });
    } catch (error) {
      this.setState({
        pageNumber: pageNum,
        isLoaded: true,
        error,
      });
    }
  }
  componentDidMount() {
    this.fetchHero(0);
  }

  /*you don't need this-> componentDidUpdate(prevState) {
    if (this.state.pageNumber !== prevState.pageNumber) {
      const fetchData = async () => {
        const response = await fetch(
          this.state.webPage + this.state.pageNumber
        );
        const data = await response.json();
        this.setState({ characters: data.results });
      };

      fetchData();
    }
  }*/
  getNextPage = () => {
    if (this.state.pageNumber < 9) {
      this.fetchHero(1);
    }
  };
  getPrevPage = () => {
    if (this.state.pageNumber > 1) {
      this.fetchHero(-1);
    }
  };
  render(
      // the rest of your code
  )
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement