Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to retain state of a revisited page? #145

Open
benny856694 opened this issue Dec 16, 2024 · 3 comments
Open

How to retain state of a revisited page? #145

benny856694 opened this issue Dec 16, 2024 · 3 comments

Comments

@benny856694
Copy link

benny856694 commented Dec 16, 2024

I want to retain the sate of the page, is there a good way?
using a singleton class to hold the sate and inject to the page?

@benny856694 benny856694 changed the title How to retain state of a revisited page How to retain state of a revisited page? Dec 16, 2024
@MattParkerDev
Copy link

Yes, a simple AppState pattern can be used if you want to load the data for a page from in memory.

public class AppState
{
	public string? MyProperty { get; set; }
}

Then yes, register it as a singleton:

// Program.cs
appBuilder.Services.AddSingleton<AppState>();

Then it can be injected into a page:

@* MyPage.razor *@
@inject AppState AppState

And used like so:

@code {
	private string? _myProperty;

	protected override void OnInitialized()
	{
		_myProperty = AppState.MyProperty;
	}
}

Be aware of the gotcha that if you bind any UI elements to properties on AppState, updating any values in AppState from a different view will not cause a re-render of the current view - you will need to manually trigger it yourself somehow.

@benny856694
Copy link
Author

seem no better way

@benny856694
Copy link
Author

Yes, a simple AppState pattern can be used if you want to load the data for a page from in memory.

public class AppState
{
	public string? MyProperty { get; set; }
}

Then yes, register it as a singleton:

// Program.cs
appBuilder.Services.AddSingleton<AppState>();

Then it can be injected into a page:

@* MyPage.razor *@
@inject AppState AppState

And used like so:

@code {
	private string? _myProperty;

	protected override void OnInitialized()
	{
		_myProperty = AppState.MyProperty;
	}
}

Be aware of the gotcha that if you bind any UI elements to properties on AppState, updating any values in AppState from a different view will not cause a re-render of the current view - you will need to manually trigger it yourself somehow.

thanks, I watched your YouTube video, great sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants