I have a simple todolist app in Blazor where when I check a todo item the list of todos are written to a json file. It works up until the last checkbox. The last checkbox won't write to the json file and won't stay checked.
I tried to write to a text file as well as called async methods and StateHasChanged, but nothing seems to work.
@page "/todo"@rendermode InteractiveServer@inject API.IApi todoApi<PageTitle>Todo</PageTitle><h3>Todo (@todos.Count(todo => !todo.IsDone))</h3><input placeholder="Something todo" @bind="newTodo" /><button @onclick="ValidFormSubmitted" class="btn btn-primary">Add Todo</button><ul class="list-unstyled"> @foreach (var todo in todos) {<li><input @key="todo" type="checkbox" @bind="todo.IsDone" @oninput="CheckboxChanged"/><input class="border-0" type="text" @bind="todo.Title" /></li> }</ul>@code { public List<TodoItem> todos = new(); public string? newTodo = ""; public async Task ValidFormSubmitted() { Console.WriteLine("Clicked"); if(!string.IsNullOrWhiteSpace(newTodo)) { todos.Add(new TodoItem { Title = newTodo }); await Task.Run(() => todoApi.Write(todos)); newTodo = string.Empty; } } protected override async Task OnInitializedAsync() { todos = await Task.FromResult(todoApi.Read()); Console.WriteLine("Initialized"); } public async Task CheckboxChanged(EventArgs e) { await Task.Run(() => todoApi.Write(todos)); await InvokeAsync(StateHasChanged); }}Here is the code for writing to a json file:
using System.Text.Json;namespace Todolist.API{ public class JsonApi: IApi { public void Write(List<TodoItem> todos) { string json = JsonSerializer.Serialize(todos); File.WriteAllText("todos.json", json); } public List<TodoItem> Read() { string filename = "todos.json"; string json = ""; List<TodoItem> todos = new List<TodoItem>(); if (File.Exists(filename) && File.ReadLines(filename).Any()) { json = File.ReadAllText(filename); todos = JsonSerializer.Deserialize<List<TodoItem>>(json); return todos; } else { File.Create(filename).Close(); return todos; } } }}