#loader + state + fetcher.Form + fetcher.load

1 messages · Page 1 of 1 (latest)

molten quiver
#

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>
astral sparrow
#

Loader is itself a state under the hood, and fetcher also has states under the hood that keep your ui up to date when changes happen

#

The only useful state here might be the setPage but you could also accomplish that with url Query Params if you wanted

molten quiver
#

Are you sure that would be enough? Doesn't sound right to me.

To make sure, do you mean this?:

const items = useLoaderData()

items.map((i) => {
  <Item {...i} />
})

<Button
  onClick={() => {
    fetcher.load(`/?index&page=${page}`)
    setPage((prev) => prev + 1)
  }}
>
  Load more
</Button>
#

How would you combine loader data with fetcher data?

molten quiver
#

And yet it still feels awkward todo. Also gets more complicated when you have e.g. filters for the data

#

Feels like I am missing something

astral sparrow
# molten quiver Feels like I am missing something

Sorry for disappearing, was mainly trying to suggest using the url a bit more to help with filtering and the like. By updating url query params you can cause a refetch of loader data. It does seem like you want an infinite scroll which I didn’t initially realize so that makes my advice a bit less applicable. Is the solution you used from that thread Sergio’s, approach? Cause that seems to me the best way to stick with remix’s approach and enable something like infinite scroll. But like a lot of people said remix isn’t super compatible with the infinite scroll idea so it’s definitely a bit awkward making it work