0

I need some help with React. As far as I know, it should be working just fine. But, it is not working. What I am trying to do is :

  • I have a list of todo.
  • You can add new todo and you can also expand the todo section.
  • When you expand the todo section, it will open up full screen.

The problem is, newly added todos are not showing up when you expand the todo. Why is that? I am basically using the same component. Why is it that the newly added todos dissapeared when todo section is expanded? And vice-versa, when you expand, add new todo and close the modal, newly added todos are not showing up. How can I make new todo persists regardless of the todo section is expanded or not.

Please, take a look at the small demo app I built.

full codesandbox link

Dane
  • 9,242
  • 5
  • 33
  • 56
Nyi Nyi Hmue Aung
  • 587
  • 1
  • 7
  • 19
  • 1
    Please include the relevant code in the body of the question, an external link can change and make the question either un-answerable in the short term, or unhelpful to later readers in the long term. – DBS Aug 16 '22 at 09:13
  • Does this answer your question? [How to keep React component state between mount/unmount?](https://stackoverflow.com/questions/31352261/how-to-keep-react-component-state-between-mount-unmount) – Dane Aug 16 '22 at 09:15

2 Answers2

2

The Todo component is not getting re-rendered, but unmounted and remounted. You have your state inside the Todo component, but each time expand changes, Todo gets unmounted and remounted inside the Dialog component. This causes it to lose its internal state. The solution would be to lift the state up in the tree, i.e., to keep the state inside Demo component.

Relevant section in docs: Lifting State Up

Dane
  • 9,242
  • 5
  • 33
  • 56
  • Thanks for answering. Is there any way to handle this without lifting the state up one level?? Unfortunately, I can't do that in my real app. Is there any other workarounds?? – Nyi Nyi Hmue Aung Aug 16 '22 at 09:15
  • To be honest, no. The component *needs* to unmount and remount as the parent node (`Dialog` & div) is being changed. You cannot detach and reattach a node to another parent keeping its internal state intact. Every instance of `todoComponent` has its own internal state. You should reconsider state handling in your real app. – Dane Aug 16 '22 at 09:22
1

You're state gets lost in case it is not managed globally or a layer above. To solve that you could take a look at Redux. It's a library for managing and centralizing application state. It is open-source, well adopted, a good library to know and can also be used for further javascript frameworks like Angular.

https://react-redux.js.org/

Chris
  • 4,403
  • 4
  • 42
  • 54