Inertia V2 + Rails - Infinite Scroll

Curated ago by @pedroaugustorduarte

Description

How to implement InfiniteScroll with Inertia V2 + Rails + Rails

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import React from "react";
import Todo from "../../components/Todo";
import {Deferred, useForm, usePage, WhenVisible} from "@inertiajs/react";

const TodosIndex = ({todos, pagy}) => {
  const {data, setData, post, processing, errors} = useForm({
    name: ""
  });

  const submit = (e) => {
    e.preventDefault()
    post('/todos')
  }

  // Needs for WhenVisible component re-render and fetch again
  const RenderWhenVisible = () => {
    if (pagy.page < pagy.last) {
      return (<WhenVisible fallback={"Loading..."} params={{
          data: {
            page: pagy.page + 1,
          },
          only: ["todos", "pagy"],
          preserveUrl: true,
        }}/>
      )
    }
  }

  return (
    <div className="container px-4 mx-auto pt-26">
      <div className="flex justify-between">
        <h1 className="text-3xl font-bold underline">
          Minha lista de tarefas
        </h1>
      </div>

      <form method="post" onSubmit={submit}>
        <div className="mb-4">
          <input name="name"
                 placeholder="Nome da tarefa"
                 className="form-input mt-1 block w-full border-2 border-handwrite border-black p-2"
                 value={data.name}
                 onChange={e => setData("name", e.target.value)}
          />
          <span className="text-red-500 text-xs">
            {errors.name && errors.name}
          </span>
        </div>

        <div className="flex items-center justify-between">
          <button type="submit" className="border-2 border-handwrite border-black p-2" disabled={processing}>
            Enviar
          </button>
        </div>

      </form>

      {todos.map((todo) =>
        <Todo todo={todo} key={todo.id}/>
      )}

      <RenderWhenVisible/>
    </div>
  )
}

export default TodosIndex;