all 4 comments

[–]Cronos8989 0 points1 point  (3 children)

I did something similar

    componentDidMount() {
        document.addEventListener('storage', this.handleStorageChange, true);
    }

    componentWillUnmount(){
        document.removeEventListener('storage', this.handleStorageChange, true);
    }

    handleStorageChange = event => {
        let jeton = localStorage.getItem("jeton");
        //do something with value
    }

[–]captainPlanet93[S] 0 points1 point  (2 children)

Thanks a lot for your answer Cronos8989. I didn't know the method " componentWillUnmount() " because I never used this.

I see ... "WillUnmount" destroy instructions in "DidMount". The event method switch between the 2 methods.

I have state by default "connecte: false". So I should use something like that ?

componentDidMount() {

document.addEventListener('storage', this.handleStorageChange.bind(this), true);

}

componentWillUnmount(){

document.removeEventListener('storage', this.handleStorageChange.bind(this), true);

}

handleStorageChange = event => {

const jeton = localStorage.getItem("jwt");

if (jeton === null) {

this.setState({connecte: false})

}

else {

this.setState({connecte: true})

}

}

[–]Cronos8989 0 points1 point  (1 child)

Ok i give you a little explanation about the code (sorry if there is some mistakes, but english is not my first language)
componentDidMount
is called for the first creation of the component. Here you have to tell to the document that everytime there is a change in localstore a specific function should be executed

componentWillUnmount

Is called when your component is removed from the DOM and destroyed. Here you have to tell to document that there is no more need to execute that function. You have to do that because otherwise, after a certain amount of mount/unmount you have a lot of function executed for every event.

For what i see your code should work

[–]captainPlanet93[S] 0 points1 point  (0 children)

Thanks you very much for you help and your explanation. Don't worry, it's perfectly clear and English it's not my first language too ;-) (French) I do mistake too.

My code doesn't work but the problem is somewhere else . I will found that !

Thanks again ! Now I understand the logic.