IWI
IWI

Reputation: 1604

Table data not rerendering after state change with useEffect and setState

I have a table with a filter. The filter is triggered by a select dropdown. I can see in the console that the list has been updated, however, I don't see the change occurring on screen

    // where the rows are rendered
    const renderAdvisors = map((advisor) => (
      <Row advisor={advisor} key={advisor.id} />
    ));
   // HOW I ORIGINALLY GET THE TABLE DATA - IS THE USEMEMO THE PROBLEM?
       const sortedAdvisors = useMemo(
    () => {
      ...
      ...
      
    },
    [arrayOrder, advisors]
  );

   // WHERE I GET MY UPDATED DATA AFTER THE FITLER (I CAN SEE THE NEW LIST IN CONSOLE
  const [filtered, setFiltered] = useState("ALL")
  
  // this useeffect causes a rerender so theoretically the new data would be rendered
  useEffect(() => { 
    filteredAdvisors = sortedAdvisors.filter(obj => obj.location === 
      filtered.toUpperCase());
    console.log('filtered advisors', filteredAdvisors, 'sortedadv', sortedAdvisors)
  },[filtered])
  
  // Below is wht changes the filter with usestate
  const onChangeFilter = (e) => {
    setFiltered(e.value)
  }
   
   return (
   ...
   ...
   // HERES WHERE I SWAP OUT THE LISTS AND AM EXPECTING A RE-RENDER BUT NONE OCCURS
    {advisors.length ?
    renderAdvisors(filteredAdvisors.length ? filteredAdvisors:sortedAdvisors)
    :
    <pw-body size="large" color="grey">Please enter a value</pw-body>
  }
  </tbody>
  ...
  )

Upvotes: 1

Views: 1696

Answers (2)

Sinan Yaman
Sinan Yaman

Reputation: 5946

Just to make it clear, I created a codesandbox. You can start typing "a" or "ab" to see how filter works. The important thing here is to store the variable inside the state, which you already solved.

Upvotes: 1

IWI
IWI

Reputation: 1604

Solved. thanks to @Sinan Yaman

I was unthinkingly using a regular variable and not a state, so the update wasnt happening.

Upvotes: 1

Related Questions