inertiajs / inertia

Inertia.js lets you quickly build modern single-page React, Vue and Svelte apps using classic server-side routing and controllers.
https://inertiajs.com
MIT License
6.56k stars 435 forks source link

[V2] Improve WhenVisible component to merge data and params props for a more flexible API #2025

Open PedroAugustoRamalhoDuarte opened 1 month ago

PedroAugustoRamalhoDuarte commented 1 month ago

Versions:

Describe the problem:

In the current implementation of the WhenVisible component, it is not possible to use both data and params props simultaneously. The issue lies in the getReloadParams function, which either returns data or params but not both. To provide a more flexible and user-friendly API, it would be ideal to merge the data prop into params when both are provided.

Steps to reproduce:

  1. Use the WhenVisible component with both data and params props.
  2. The getReloadParams function will only consider data and ignore params.
<WhenVisible fallback={"Loading..."} data={["todos", "pagy"]} params={{
  data: {
    teste: true,
    page: pagy.page + 1,
  },
  preserveUrl: true,
}} />

Actual code

https://github.com/inertiajs/inertia/blob/88a765b3a3736a63b6619863b9bd872a5327f0d6/packages/react/src/WhenVisible.ts#L24

Expected behavior:

When both data and params are provided, the function should merge them into a single object, allowing both to work together.

A initial implementation for React can be something like:

const getReloadParams = (): Partial<ReloadOptions> => {
  const reloadParams: Partial<ReloadOptions> = { ...params }

  if (data) {
    reloadParams.only = (Array.isArray(data) ? data : [data]) as string[]
  }

  return reloadParams
}
shankiflang commented 1 month ago

Hi! I have the problem too! I want to set data to my feed and use params to manage the currentPage number update but it doesn't work.

irsyadadl commented 1 month ago

When using params, the data actually should be optional. Right now it doesn't.

devswert commented 1 week ago

As a temporal fix, you can set the data prop as an empty string and Inertia will use the params prop

<WhenVisible fallback={"Loading..."} data={''} params={{
  data: {
    teste: true,
    page: pagy.page + 1,
  },
  preserveUrl: true,
  only: ["todos", "pagy"]
}} />