Skip to content

RTK Query - Infinite loop when arg is nested object #1526

@lukascivil

Description

@lukascivil

The problem

image

The problem infinite loop with multiple calls occurs when filter is an object inside another object, which assembles arg.

  const [filter, setFilter] = useState({email: "[email protected]"})

If filter is a direct value, as string or number, or the object with the same key, the problem does not occur, example:

  const [filter, setFilter] = useState("[email protected]")

The "useGetUsersQuery" (example below) hook will make multiple calls as if it were in loop.

I don't know if this is expected behavior with wrong use or a possible bug, however I would like to understand the hook behavior based on prev Arg and next Arg, how does Hook handle this?

Full example with infinite loop

export const TabLocalList: FC = () => {
  const [filter, setFilter] = useState({ email: '' })
  const currentSort = { field: 'created_at', order: 'ASC' }
  const { isFetching, data, refetch } = useGetUsersQuery({
    filter,
    pagination: { page: 1, perPage: 50 },
    sort: { field: 'created_at', order: 'ASC' }
  })

  return (
    <LocalList
      isLoading={isFetching}
      data={data?.data}
      onRefresh={refetch}
      onSubmit={values => {
        setFilter(values as any) // {created_at_start: "..."}
      }}
      sort={currentSort}
      filters={[<TextInput source="created_at_start" validate={required()} />]}
    >
      <Datagrid>
        <TextField source="id" label="Id" />
        <TextField source="email" label="E-mail" />
      </Datagrid>
    </LocalList>
  )
}

I did some examples and got different results

      onSubmit={values => {
        // Works ok
        // setFilter({ email: values?.email } as any)

        // Works ok (If values were {email: "..."}) , same key with diferent value
        // setFilter(values as any)

        // Works ok
        // setFilter({ email: '55' } as any) // OK

        // Crash with infinite loop, add a new prop
        // setFilter({ email: '55', created_at_start: '' } as any)

        // Crash with infinite loop, remove email and use new key for diferent filter
        // setFilter({ created_at_start: '' } as any)
      }}

From the above results, I believe the internal check to see if the args have changed may be causing this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    RTK-QueryIssues related to Redux-Toolkit-Query

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions