TanStackT
TanStack13mo ago
34 replies
inner-olive

Why does my form default value not re-render?

export const Route = createFileRoute('/product-backlog/task/edit/$taskID')({
  component: EditTask,
  loader: ({ params }) => {
    return fetchTask(params.taskID)
  }
})

function EditTask() {
  const task = Route.useLoaderData()
  const { taskID } = Route.useParams()

  const navigate = useNavigate({ from: "/product-backlog/task/edit/$taskID" })
  const navigateTo = () => { 
    navigate({ to: "/product-backlog" })
  }

  const editTask = async (formData: FormData) => {
    // Edit Task
    navigateTo()
  }

  return <TaskEditor task={task} action={editTask} navigateTo={navigateTo} deleteTask={deleteTask} />
}


function TaskEditor(props: TaskEditorProps) {

    return (
        <section>
            <form action={props.action}>
                <input defaultValue={props.task?.name || ""} />
                <button>Save</button>
            </form>
        </section>
    )
}

export default TaskEditor


Initially, I am in "/product-backlog" route. I navigate to "/product-backlog/task/edit/1" to edit my task name. Once I click the "Save" button, the edit is successful and I am able to observe the changes in my "/product-backlog" route. However, when I navigate back to "/product-backlog/task/edit/1", the default values of <input /> still shows the previous value, but if I were to navigate to "/product-backlog" and back to "/product-backlog/task/edit/1" again, this time the default values of <input /> shows the updated value.

I tried console.log() the props.task in <TaskEditor /> and I see that it logs 2 different values, the old value and the new value (2 times old, 2 times new in strict mode), while displaying the old value.

I thought by navigating from "/product-backlog/task/edit/1" to "/product-backlog" will cause my <TaskEditor /> to unmount, and so navigating back to "/product-backlog/task/edit/1" will cause a re-render and display the correct value but it didn't

Can anyone explain to me what is happening behind the scenes? Thank you
Was this page helpful?