Sign in
Log inSign up

reactjs not re-rendering in the browser

jim toby's photo
jim toby
·Oct 18, 2018

In my code, whenever I call a setState it seems like it is indeed changing the state but it is not being reflected in the browser. Here is my function that calls setState. This function deletes an element from an array called rows1 in my state:

removeFromRowsById = index => {
   console.log("IN REMOVE FUNCTION");


   const newList = [...this.state.rows1];
   newList.splice(index, 1);
   this.setState({ rows1: newList });
};

Here is part of my render method where I use the contents of rows1.

 return (
  <Paper className={classes.root}>
    <EnhancedTableToolbar numSelected={selected.length} />
    <div className={classes.tableWrapper}>
      {console.log("UPDATED ARRAY:", rows1)} //I PRINT IT HERE
      <Table className={classes.table} aria-labelledby="tableTitle">
        <EnhancedTableHead
          rows={rows1} //I USE IT HERE
          order={order}
          orderBy={orderBy}
          onRequestSort={this.handleRequestSort}
        />
         ......

Notice where I log rows1 before I assign rows to it. In the console, at first it prints rows1 without the deleted value, and than after the state has changed I guess, it re-renders and prints rows1 with the deleted value, meaning there is one less items in the list which is good. The problem is, this is not being reflected in the browser. It's like as though nothing changes

NOTE: When I copy the value of rows1 after the change, and assign rows to it, it properly reflects it so I know I'm assigning the proper variable. How do I fix this issue.

I tried using the second form of setState found HERE like this:

this.setState((state) => ({ rows1: newList }));

but it's still the same issue.

The only way I can get around this is by adding a boolean in the callback of removeFromRowsById and setting it to true once the state is updated. And than I'd need to only return in the render method when the condition is true, otherwise I return something else. I don't think that's the proper way to do it though because it should re-render properly with the new value of rows1 but it seems like it keeps the old value assigned to row. Please share your thoughts with me and let me know if things are unclear. I didn't want to post my whole code because it's pretty long.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct