DVM
DVM

Reputation: 1238

Keeping timer in sync across components

Bit of background: I'm trying to learn a React and am building a small app with next (using a template from a tutorial I did a while ago). I've recently run into an issue where I need to keep a timer in synch between 2 components that are not in the same hierarchical structure.

I have an Item component that displays a few details about that item(description, title, etc) in a more concise way (a tile displaying just part of the entire item info). If I click on the Item tile, i have a next.js Link component that looks like this:

 <Link href={{pathname: "/item", query: { id: item.id }}}>
    <a>{item.title}</a>
 </Link>

which will redirect me to a new page containing an ItemDetails component which just displays all the information for that item in more detail and using the entire page instead of just the tile used for the Item.

As mentioned above, the issue is that I want to have a countdown timer that is kept in sync between Item and ItemDetails (can be started, stopped, etc from either of them and it's state would be reflected in the other component). Initially, I thought of using MobX and creating a store and using that as a way to keep the same state between the two components. However, the problem with that is that I have multiple instances of the Item component, each pointing to their own ItemDetails and by using a single store that would just share the state of the first started timer between all Items (might be wrong here though since MobX is something i just started reading about yesterday ^^).

My question is, what would be the best way to approach this issue? Is this doable using Mobx plus stores or is it an issue of how the app is structured (eg: find a way to make Item and ItemDetails part of the same hierarchical structure?

Any help would be appreciated.

Upvotes: 1

Views: 899

Answers (1)

Dane Stevens
Dane Stevens

Reputation: 545

Here's a working example using React "context" to share the data between components and refs to keep time across re-renders:

https://codesandbox.io/s/silly-http-h25dr?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 2

Related Questions