GangstaGraham
GangstaGraham

Reputation: 9385

ViewDidAppear-Like Method For JS/React?

Say, there are two tabs with the same webpage open. On one tab, I make some change in localStorage, then, when I go to the other tab, I'd like to see that change without having to reload the page.

One way that I have thought to do this is by using a setInterval method, but for my application I don't really need to check for updates every 3-5 seconds so I don't feel this approach is ideal.

I am using React. TLDR: Is there a good way to update data as soon as I open the tab of a previously-loaded webpage?


Side Note For iOS Folks: On iOS, there is a viewDidLoad method (which from my understanding is similar to componentDidMount), and there is a viewDidAppear method (so I am basically, asking for the React/JS version of viewDidAppear?)


In regards to the possible duplicate question: To me, it seems fairly different, and this question is more React.js focused.

Upvotes: 2

Views: 489

Answers (3)

GangstaGraham
GangstaGraham

Reputation: 9385

I added the following lines of code to my main component.

In componentDidMount:

document.addEventListener("visibilitychange", this._callbackFunc, false);

In componentWillUnmount:

document.removeEventListener("visibilitychange", this._callbackFunc, false);

Upvotes: 0

Brigand
Brigand

Reputation: 86260

Use the page visibility api or just window's focus event. I recommend having a backup timer set to a minute or so... these events can be finicky.

There's nothing react specific about it other than binding to global events.

Upvotes: 1

Shai
Shai

Reputation: 25595

You can use jQuery and listen to localStorage on-change events:

 $(window).bind('storage', function (e) {
     console.log(e.originalEvent.key, e.originalEvent.newValue);
 });

This way, once a key in the local storage changes, you can reflect it in the 2nd tab.

If you're using react, then make sure you're rendering a component in your main component's render() function that makes use of you main component's state object. Once local storage has changed, update the state accordingly and react will take care of the rest.

Upvotes: 1

Related Questions