T
TanStack10mo ago
quickest-silver

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
})
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
})
2 Replies
genetic-orange
genetic-orange10mo ago
you would need to use a useEffect
quickest-silver
quickest-silverOP10mo ago
yes, that's what i used, but i always hear "you shouldn't use useEffect" so i was wondering if there's a better way

Did you find this page helpful?