So, I have thoroughly read and tried everything in the documentation, checked the example apps and looked here for an answer - yet still unsure how to solve it.
Use case: feed (list of items) with append-able pagination (button "load more"). Each item has a number of votes and a button to add/remove your vote.
I did a loader function that gives the items and fetcher.Form for each vote button to a separate route action (items/$id/votes).
Now, all is good, but as I understood, to add such pagination, it would mean to use useState to hold all the items and useEffect to combine fetched results with the state.
This is where it gets weird. Since clicking "vote" submits the form, the loader loads the changed data, which does not match with the state data anymore.
Am I going wrong about this? What would be the correct way to do it?
const initial = useLoaderData()
const [items, setItems] = useState(initial.items)
const fetcher = useFetcher()
const [page, setPage] = useState(2)
useEffect(() => {
if (fetcher.data) {
setItems((prev) => [...prev, ...fetcher.data.items])
setPage((prev) => prev + 1)
}
}, [fetcher.data])
<Button
onClick={() => {
fetcher.load(`/?index&page=${page}`)
}}
>
Load more
</Button>