Home > Enterprise >  My React function gets called twice, with the second call setting values incorrectly
My React function gets called twice, with the second call setting values incorrectly

Time:09-18

i have a function that calculates pages and page buttons based on an api. Inside the buttons get rendered and they have an onClick function. When i click the button, this is supposed to happen:

  • sets the current page number and writes it into state
  • calls the api which gets text elements to display according to current page
  • evaluates page buttons and numbers based on api and marks the current page with a css class

event handler:

handleClick(event) {
        let currentPage = Number(event.target.id)
        localStorage.setItem("currentPage", currentPage)
        this.setState ({
            currentPage: currentPage
        })
        this.fetchApi() 
    }

then i'm returning the component that deals with pages:

return(
      <div>
          <Paging 
              data = {this}
              currentPage = {this.state.currentPage}
              state = {this.state}
              lastPage = {this.state.lastPage}
              handleClick = {this.handleClick}
           />
       </div>
)

and the component looks like this:

function Paging(props) {
    const apiPaging = props.state.apiPaging
    const apiPagingSliced = apiPaging.slice(1, -1) 
    
    const renderPageNumbers = apiPagingSliced.map((links, index)  => {
        return <button key={index} id={links.label} 
                onClick={(index)=>props.handleClick(index)} 
                className={(links.active ? "mark-page" : "")}
                >{links.label} {console.log(links.label) }
                </button> 
    })

    return ( 
         <div id = "page-nums"> 
              {renderPageNumbers}
         </div>
           )

So what happens is that Paging() function gets called twice. There is a handy value inside the api called "active" (links.active) which is a boolean, and if set to true, means that the page is the current page. i then add a class "mark-page" on to highlight that i'm currently on that page. If i {console.log(links.label)} i see that it's invoked twice, first being the correct values and second being the previously clicked values. So it works correctly only if i reload the page again.

i.e if i click page 2,it stays on page 1 and marks page 1. if i then click page 3, it marks page 2. and (afaik) Paging() gets only invoked once, at the end of my only class (Body).

I've been at it yesterday and today and have no idea anymore.

CodePudding user response:

change your handleClick function to this.

handleClick(event) {
window.scrollTo({
  top: 0,
  behavior: 'smooth',
});

if (event.target.id >= 1) {
  let currentPage = Number(event.target.id);
  localStorage.setItem('currentPage', currentPage);
  this.setState({
    currentPage: JSON.parse(localStorage.getItem('currentPage')),
  },()=>{
    this.fetchApi();
  });
}

}

in your fetchApi function you reference currentPage as below. const apiQuery = JSON.parse(this.state.currentPage); But it hasn't updated yet.

see https://reactjs.org/docs/react-component.html#setstate

  • Related