0

Here is my code, I am using React: I am using Local Storage in order to persist the state even after page refresh and to remain on the same page.

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = localStorage.getItem("app_state") ? localStorage.getItem("app_state") : {
            account: {
                email: "",
                password: ""
            },
            errorMessage: "",
            token: "",
            authenticated: false
        };

    }






    notLoggedInhomePage = () =>{

        if(!this.state.authenticated) {
            return (
                <form onSubmit={this.handleSubmit}>
                    <br/>
                    
                        <label>Email Address</label>
                        <input type="text" value={this.state.account.email} onChange={this.handleChange} name="email"/>
                        
                        <label>Password</label>
                        <input type="password" value={this.state.account.password} onChange={this.handleChange} name="password" />

                    <div>
                        {this.state.errorMessage}</div>
                    <br/>
                    <Button type="submit"  onClick={() => {
                        this.someFunction(String(this.state.account.email));
                    }}>Sign In</Button>
                </form>
            );
        }else{
            return(<Redirect to="/items/somelink" />);
        }
    }


    componentDidUpdate(prevProps, prevState){
        if(this.state.token !== prevState.token){ //set a new state if token changes
            localStorage.setItem("app_state", this.state);
        }
    }
    
    
}


export default App;

Here is the error that I am getting:

error Capture

error Capture2

It is saying that the email is undefined, what is the reason behind such error message, and why/how is the email undefined, even though it's defined as an empty string in the state.

What is a possible fix to the above ?

2 Answers2

1

local storage will only return String. not object or array. you need to parse it before assigning it to state JSON.parse(localStorage.getItem(app_state))

let appState = localStorage.getItem(app_state)
if(appState) {
  appState = JSON.parse(appState)
}

In you code

state = getState()

const getState =() => {
  let appState = localStorage.getItem(app_state)
  if(appState) {
     return JSON.parse(appState)
  } else {
    return {
            account: {
                email: "",
                password: ""
            },
            errorMessage: "",
            token: "",
            authenticated: false
        };
  }
}
sojin
  • 2,158
  • 1
  • 10
  • 18
0

Using setItem inserts a DOMstring value into local storage, getItem returns said DOM string (MDN), when I run your code snippet it returns "[object Object]", you can get around this by using

localStorage.setItem("app_state", JSON.stringify(this.state));

And then retrieving the data as:

this.state = localStorage.getItem("app_state") ? JSON.parse(localStorage.getItem("app_state")) : {
            account: {
                email: "",
                password: ""
            },
            errorMessage: "",
            token: "",
            authenticated: false
        };
mpmcintyre
  • 614
  • 5
  • 16
  • The data is persisted in localStorage, but when I refresh the page, I don't remain on the same page, instead it redirects me to the /items/somelink, What is the reason behind that ? –  Sep 06 '21 at 19:39
  • You are checking for authenitication before rendering your form with `if(!this.state.authenticated)`, If the user is authenticated it redirects them. My guess is that you were logged in when testing it and it redirected you with `return()`. – mpmcintyre Sep 07 '21 at 03:50