Skip to content

Commit

Permalink
fix optimistic update
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoburniske committed Feb 23, 2024
1 parent 6b5bb2b commit dc0d8d0
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions example/start-csr/src/pages/interactive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,22 +136,26 @@ fn AddTodoEntry() -> impl IntoView {
contentX.set(Default::default());

// Find a unique id for the todo.
let temp_id = all_todos
.peek_query_state(&AllTodosKey)
.and_then(|todos| {
let todos = todos.data()?;
let id = todos.iter().map(|t| t.id.0).max()?;
Some(id + 1)
})
.unwrap_or(0) as u32;
let temp_id = {
let temp_id = all_todos
.peek_query_state(&AllTodosKey)
.and_then(|todos| {
let todos = todos.data()?;
let id = todos.iter().map(|t| t.id.0).max()?;
Some(id + 1)
})
.unwrap_or(0) as u32;

TodoId(temp_id)
};

// Optimistically add the todo to the list
all_todos.update_query_data_mut(AllTodosKey, {
let title = title.clone();
let content = content.clone();
|todos| {
todos.push(Todo {
id: TodoId(temp_id),
id: temp_id,
title,
content,
completed: false,
Expand All @@ -165,7 +169,6 @@ fn AddTodoEntry() -> impl IntoView {

// Replace the optimistic todo with the real todo
all_todos.update_query_data_mut(AllTodosKey, {
let temp_id = todo.id;
move |todos| {
todos.retain(|t| t.id != temp_id);
todos.push(todo);
Expand Down

0 comments on commit dc0d8d0

Please sign in to comment.