Skip to content

How to select a row after state update? #3863

@adi-works

Description

@adi-works

Describe the bug

I have two components, a modal and a table component (MUI 5 + react-table). I update the server state from the modal, so eventually a new row is added to the table. However, when I try to select the row immediately after updating the server state (even with an optimistic update), a racing condition occurs and I get an exception from the react-table hook.

This is where I update the state, in a modal component.

const patchResult = dispatch(
  api.util.updateQueryData('listCharactersByProject', { projectId }, (draft) => {
    draft.push(newCharacterInput as CharacterFromListQuery);
  })
);

const newCharacter = await createCharacter({ input: newCharacterInput })
  .unwrap()
  .catch(() => patchResult.undo());

const episodeCast = await createEpisodeCast({
  input: {
    episodeId: episodeId!,
    characterId: newCharacter?.id!,
    orderIndex: newCharacter?.orderIndex!,
  },
}).unwrap();

if (episodeCast?.characterId) {
  modal.resolve({ characterId: episodeCast.characterId, isNewCharacter: true });
  modal.remove();
}

Then, in the table component I do this:

const handleAddCharacter = useCallback(async () => {
  clearCharacterSelection();
  const { characterId, isNewCharacter } = (await NiceModal.show(AddCharacterModal, { projectId, episodeId })) as {
    characterId: string;
    isNewCharacter: boolean;
  };
  if (isNewCharacter && characterId) {
    tableRef.current?.toggleAllRowsSelected(false);
    tableRef.current?.toggleRowSelected(characterId, true); // throws an error
    tableRef.current?.scrollToRow(characterId);
  }
}, [projectId, episodeId, clearCharacterSelection]);

Your minimal, reproducible example

Pasted some code above.

Steps to reproduce

Update the table state and then try to select the row.

Expected behavior

The newly created row should be rendered and selected.

How often does this bug happen?

No response

Screenshots or Videos

No response

Platform

macOS

react-table version

v7.6.3

TypeScript version

v4.5.4

Additional context

No response

Terms & Code of Conduct

  • I agree to follow this project's Code of Conduct
  • I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions