Next.js Discord

Discord Forum

State management and dynamic routes

Unanswered
Tamás Soós posted this in #help-forum
Open in Discord
Hi. I'm working on a web app using Next.js. It's main purpose is to let me easily create and edit some entities related to a task. The entities live in a hierarchy. The actual entities don't matter, I'll use an IoT related example. Let's say we have Device -> Firmware version -> Available parameters as the hierarchy.

Let's say the directory structure according to the hierarchy is as follows:
...
- layout.tsx
- navBar.tsx
- deviceList.tsx
- page.tsx
  - device
    - [deviceId]
      - layout.tsx
      - firmwareVersionList.tsx
      - page.tsx
      - firmware
        - [firmwareId]
          - layout.tsx
          - parameterList.tsx
          - page.tsx
          ...
      ...
...


The index page would show the list of devices, while the layout provides the nav bar for the entire app. The page inside the [deviceId] folder shows the list of firmwares available for the selected device.

The nav bar has search components to allow the user to quickly switch to any device / firmware / parameter. It looks something like the first screenshot. The search components become enabled as the relevant sub route is visited, so the search devices component is always enabled, the search firmware version component is enabled inside /device/[deviceId]/**, etc... Additionally the selected entity is shown on the search component (2nd screenshot).

The appropriate entity is fetched in the corresponding layout that lives in the right sub route, for example the selected device is collected here:
...
- layout.tsx
- navBar.tsx
- deviceList.tsx
- page.tsx
  - device
    - [deviceId]
      - layout.tsx <- Get device from db
      - firmwareVersionList.tsx
      - page.tsx
      ...
...


Then currently the collected device object is shared with components in the sub routes after that via a context.

My issue is with figuring out how to provide the selected device to the search device component in the nav bar.

2 Replies

AFAIK we can't read the dynamic IDs in the layouts above a specific route. Right now there's a context provider wrapping the nav bar and a nested provider wrapping the relevant sub route that are kept somewhat in sync via useEffects. Here's the summary of what I'd like to achieve:
- Share these entities globally so that all dependent components have easy access to them.
- Initialise the entities in particular sub routes outside which they are undefined by default
- The value the entities are getting initialised with should come from the server and be fetched in a server component
- Components outside the sub route providing the entity should be able to access the global value as for example Device | undefined
- Components inside the sub route providing the entity should be able to access the global value as simply Device
- State updates should rerender dependent components everywhere in the tree.