question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

rtk query: `isSuccess` never becomes `true` and `status` is reset to `uninitialized ` upon first mount

See original GitHub issue

Hi, I notice that upon first rendering of a react component with the following function body, the very first time isSuccess never returns with true after a successful request (all 3 crud methods suffer from the same):

export default function ({
  match: {
    params: { teamId },
  },
}: RouteComponentProps<Params>): React.ReactElement {
  useAuthzSession(teamId)
  const [formData, setFormData] = useState()
  const [deleteId, setDeleteId]: any = useState()
  const [create, { isLoading: isLoadingCreate, isSuccess: okCreate, status: statusCreate }] = useCreateTeamMutation()
  const [update, { isLoading: isLoadingUpdate, isSuccess: okUpdate, status: statusUpdate }] = useEditTeamMutation()
  const [del, { isLoading: isLoadingDelete, isSuccess: okDelete, status: statusDelete }] = useDeleteTeamMutation()
  const { data, isLoading, error } = useGetTeamQuery(
    { teamId },
    { skip: !teamId || isLoadingCreate || isLoadingUpdate || isLoadingDelete || okCreate || okUpdate || okDelete },
  )
  useEffect(() => {
    if (formData) {
      setFormData(undefined)
      if (teamId) update({ teamId, body: omit(formData, ['id']) as typeof formData })
      else create({ body: formData })
    } else if (deleteId) {
      setDeleteId()
      del({ teamId: deleteId })
    }
  }, [formData, deleteId])
  // END HOOKS
  // console.log('statusCreate: ', statusCreate)
  // console.log('isLoadingCreate: ', isLoadingCreate)
  // console.log('okCreate: ', okCreate)
  // console.log('statusUpdate: ', statusUpdate)
  // console.log('isLoadingUpdate: ', isLoadingUpdate)
  // console.log('okUpdate: ', okUpdate)
  console.log('statusDelete: ', statusDelete)
  console.log('isLoadingDelete: ', isLoadingDelete)
  console.log('okDelete: ', okDelete)
  if (okDelete || okCreate || okUpdate) return <Redirect to='/teams' />
  const team = formData || data
  const comp = !(isLoading || error) && <Team team={team} onSubmit={setFormData} onDelete={setDeleteId} />
  return <PaperLayout loading={isLoading} comp={comp} />
}

Running it subsequently all works well. Seems like a bug.

Log output first run (hard reload first of browser window), by providing deleteId:

statusDelete:  uninitialized
isLoadingDelete:  false
okDelete:  false
statusDelete:  pending
isLoadingDelete:  true
okDelete:  false
statusDelete:  pending
isLoadingDelete:  true
okDelete:  false
[Violation] Forced reflow while executing JavaScript took 40ms
statusDelete:  uninitialized
isLoadingDelete:  false
okDelete:  false
statusDelete:  uninitialized
isLoadingDelete:  false
okDelete:  false
[Violation] Forced reflow while executing JavaScript took 31ms

Second run:

statusDelete:  uninitialized
isLoadingDelete:  false
okDelete:  false
statusDelete:  pending
isLoadingDelete:  true
okDelete:  false
statusDelete:  pending
isLoadingDelete:  true
okDelete:  false
statusDelete:  fulfilled
isLoadingDelete:  false
okDelete:  true

Version used:

"@reduxjs/toolkit": "^1.8.0",
"react-redux": "^7.2.6",

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:26 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
phryneascommented, Mar 27, 2022

You seem to be running the hooks’ trigger functions outside of a useEffect, just in the component body.

That means, on every render, either update or create will be triggered - as a consequence, the component rerenders to track the new mutation that was just triggered - and triggers another mutation. You just have an endless loop, and since always the latest mutation is being watched, it will never go beyond loading.

And if we assume you just skipped an event handler here: since every mutation is tracked individually, you will never see the result of a mutation that was triggered in another component. Every component will start out as uninitialized.

Imagine having three “send money” buttons - you would not want all of them to show “sending money” and “success” if you click one of them.

1reaction
phryneascommented, Mar 28, 2022

I found the quirk: I created middleware that listens to mutations and sets a global dirty flag which caused in between re-renders. But I assumed that would be handled without problems. I just migrated from an openapi-axios setup that was not backed by a global store such as redux, and it would never complain about these things. I am not really happy with the finicky nature of redux now that I think of it. It has to do with the fact that redux is decoupled from react and its reflows I think. It would be great if redux could deal with reflows in between state changes. Or can it? What am I overlooking?

The problem here is not with Redux. The problem here is that you bound things that should be bound to something like “a user clicks a button” into the render lifecycle of React instead on a button event.

So you are heavily relying on React rerendering at very certain points - and that’s just never a given. React renders when React wants and going forward that behaviour can and will always change. If you want to trigger a http request, do it in a click handler, not in a flimsy chain of setState - useEffect, which relies on the right things rendering in the right order (and which could trigger the useEffect multiple times when you don’t want it to be triggered), over multiple components.

Right now, React is starting to trigger every useEffect twice in strict mode, to make sure that doesn’t cause problems. In your case it would save the form twice etc.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Skip true option returns uninitialized state even if Im initializing ...
Found a solution using useQueryState : const Deployment = ({ environment }: { environment: Environment }) => { const valueWithSkipping ...
Read more >
Conditional Fetching | Redux Toolkit
Conditional Fetching. Overview​. Query hooks automatically begin fetching data as soon as the component is mounted.
Read more >
Queries - Redux Toolkit
RTK Query > Usage > Queries: fetching data from a server. ... Allows forcing the query to always refetch on mount (when true...
Read more >
API Slices: React Hooks | Redux Toolkit
Since this specifically depends on React itself, RTK Query ... from the mutation call and reset the result to the uninitialized state
Read more >
Redux Essentials, Part 8: RTK Query Advanced Patterns
As with adding posts, the first step is to define a new mutation endpoint in our API slice. This will look much like...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found