TanStackT
TanStack14mo ago
2 replies
sacred-rose

Edit and update loader data / Update useState after router.invalidate()

Hi, i want to build a page with a router loader where the user can edit an <input> and the backend is supposed to simply append the string "foo". When the user hits save, a POST request saves the data and nothing but 200 OK is returned.
To update the view, i want to call router.invalidate() to update using a GET request.
This works up until the useState for the <input> because useState ignores when it's parameter changes value.

How do i solve this issue? Is there a best practise for being able to edit and update data from a loader?

Example code:
const MyRoute = () => {
  const loaderData = useLoaderData({ from: "..." })
  const router = useRouter()

  const [text, setText] = useState(loaderData.text)
  // how do i update ☝ this after the reload through invalidate()?

  const handleSaveButton = async () => {
    await fetch("/api/save", /* ... */)
    await router.invalidate()
  }
  // ...
}

export const Route = createFileRoute("/some-route")({
  loader: () => fetch("/api/get"),
  component: MyRoute
})
Was this page helpful?