0

When the user switch from differenct tab in react, I want to clear the cached articles store in state, I define the artcle state using react hooks like this:

const Index: React.FC = (props) => { 
  const [localArticle, setLocalArticle] = useState(new Map<number, any>());
}

when the tabs changed, I want to clear the state like this:

 const onChange = (key: string) => {
    setLocalArticle(new Map<number, any>());
 }

it seems did not work, after set artcle to the new map with 0 element, the legacy element still stay in the state. what should I do to clear the state? I tried to debugging, the set not override the map:

enter image description here

Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • 1
    Please cut this down to a [mre], ideally in a runnable Stack Snippet. – jonrsharpe Aug 05 '22 at 14:56
  • Note _reproducible_. What makes you think the `new Map` isn't being used? – jonrsharpe Aug 05 '22 at 15:04
  • And why exactly did you think calling `setLocalArticle` would immediately reassign `localArticle`? ([Yet another](https://stackoverflow.com/questions/linked/54069253?lq=1)) dupe of the canonical https://stackoverflow.com/q/54069253/3001761. – jonrsharpe Aug 05 '22 at 15:08
  • I known it async, but how to capture the complete event? or using then to do something when the setState complete. what should I do? – Dolphin Aug 05 '22 at 15:10
  • Read the linked post, which explains all of this. – jonrsharpe Aug 05 '22 at 15:11
  • I have read the answer, but the useEffect will see the new value the next render, that's not work for me because I need to use the localArticle to do some logic. is it possible to change the value sync? – Dolphin Aug 05 '22 at 16:07
  • Well think about it - you already **have** the new value, because you're passing it to `setLocalArticle`. – jonrsharpe Aug 05 '22 at 16:07

0 Answers0