DioxusLabs / DioxusLabs/dioxus

Add State To Navigation

Open
#3,874 2 comments 0 reactions 0 assignees View on GitHub
enhancement router
Dominant language
Rust
Stars
39.1k
Forks
1.9k
Avg merge
4d 10h
Merged PRs (30d)
4

Description

## Feature Request

State should be able to be preserved through navigation. E.g. api

1. Go to new route with the provided state
```rust
let state = ...;
use_navigator().push_with_state(Route::Index {}, state);
```
2. Set state for current route.
```rust
let state = ...;
use_navigator().set_state(state);
// E.g. Then can move to new route
// use_navigator().push(Route::Index {});
```
3. Get the state for the current route
```rust
let state = use_navigator().get_state();
```
4. Go to the previous route with preserved state
```rust
use_navigator().go_back_with_state();
```
5. Drop state
```rust
use_navigator().clear_state();
```

## Implementation

Use the [history api](https://developer.mozilla.org/en-US/docs/Web/API/History_API), but don't store the state in the history api. Instead keep the state in an in-memory state store and have a history api hook that adds and pops states. Serde would not be needed in this case. Any type `Clone + 'static` could be accepted in `set_state`, and an `Option>` is returned from `get_state`.

### Additional Considerations

It may be performant to switch to `Clone + Send + Sync + 'static` as input. Then output could return `Arc>>>`, which would avoid unneeded clones.

---
If we decide to go the `Option>` route. It may be wise to add these methods as well that do not require a clone.

6. Mutate state without clone (Will panic if `with_state_mut` or `with_state` is called again before closure finishes)
```rust
let value = use_navigator().with_state_mut(|state| { 1 });
```
7. Read state without clone (Will panic if `with_state_mut` called again before closure finishes)
```rust
let value = use_navigator().with_state(|state| { 1 });
```

---
In either `Arc>>>` or `Option>` we should likely actually return a wrapper struct with convenience methods.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.