Home > OS >  react native useState become empty when other state change
react native useState become empty when other state change

Time:03-06

I have state like this

const [username,setUsername] = useState("")
const [password,setPassword] = useState("")
const [page,setPage] = useState("")

there is only one text input in entire page in page 1 with prev and next bottom buttons

enter user name

in page 2 with prev and next bottom buttons

enter password

but when I move from page1 to page 2 or vice verse text input field become empty.

I am just hiding textinput according to page value

CodePudding user response:

If these states are part of your Page1, whenever you are switching to Page2 you are unmounting Page1 and lifetime of states is till the time Page1 is mounted. Next time you are opening Page1 that is complete new fresh Page1.

If you want states should be persisted even on unmounting of pages you can go with following approaches:

1- Lift the state up keep the states to parent component and pass the values/setter functions to the page.

const Dashboard=()=>{
            const [username,setUsername] = useState("")
            const [password,setPassword] = useState("")
            const [page,setPage] = useState("")  
            const [activePage,setActivePage] = useState(0);
            return(<div>
                  {activePage===0?<Page1  username={username} setUserName={setUserName}/>:null}
                 {activePage===1?<Page2  password={password} setPassword={setPassword}/>:null}
                <button onClick={()=>{setActivePage(value=>value-1)}}>PREV<div/>
                <button onClick={()=>{setActivePage(value=>value 1)}}>NEXT<div/>
                </div>)
            }

This way you are not unmounting parent component so state will not be on page changing.

2- Use any central state management library (redux/mobx/context)

CodePudding user response:

The state will NOT stay alive longer then your component (I mean, whenever you change current page, the previous page is destructed).

What you seem to be aiming for can be called "persistent" state, or Application-wide state.

Redux is one of such persistent state implementions: https://redux.js.org/introduction/getting-started

  • Related