Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
dispatch called inside useImperativeHandle doesn't call action

I have a component with a save button

<Button onClick={() => requestSaveAsync()}>Save</Button>

I also need to be able to call requestSaveAsync from the top level of the app, so I added a useImperativeHandle hook inside a custom hook called useEditRow

interface Props {
    ref: MutableRefObject<{
        addItem: () => void
    }>
}

const useEditRow = (props: Props) => {
    useImperativeHandle(props.ref, () => ({
        addItem: () => requestSaveAsync()
    })
}

The useEditRow hook is inside of an OrderItemTable component

const OrderItemTable = forwardRef(function OrderItemTable(props: Props, ref: MutableRefObject<any>) {
    const editRow = useEditRow({
        ref: ref
    })
})

The requestSaveAsync method uses useMutation from react-query

useMutation(mutateFn, {
  onSuccess: () => dispatch({type: 'clear', name: 'row'})
})

Clear row sets the state to initial state. If requestSaveAsync is called by clicking the button, the row is cleared. If I call it through the parent component, the onSuccess function is called, but the dispatch doesn't do anything. If I put a breakpoint on the dispatch function, I see the following code about to called from react_devtools_backend.js

  useReducer: function (a, b, e) {
    a = F();
    b = null !== a ? a.memoizedState : void 0 !== e ? e(b) : b;
    z.push({
      primitive: "Reducer",
      stackError: Error(),
      value: b
    });

    // devtools show the empty function on this line will be executed next
    return [b, function () {}];
  },

At first I thought that maybe useImperativeHandle was using stale state, so I tried returning {...initialState} instead of initialState. This didn't seem to help. I tried adding the dependencies array suggested by react-hooks/exhaustive-dep. That didn't help. Does anyone know why when dispatch is called from useImperativeHandle, the state doesn't update?

Here is a codesandbox with some of the basic ideas that were shown abo.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your useImperativeHandle hook doesn't appear to be using the forwarded React ref. In other words, React refs are not regular React props that can be accessed by children components.

You should use React.forwardRef to correctly forward any passed refs on to the function component.

React.forwardRef Forwarding Refs

You didn't include your function component but if you follow the examples in the links provided it's fairly trivial to figure out.

Example:

const MyComponentWithSaveButton = (props, ref) => {
  useImperativeHandle(ref, () => ({
    addItem: requestSaveAsync,
  }));

  const requestSaveAsync = () => { .... };

  ...
};

export default React.forwardRef(MyComponentWithSaveButton);

Notice here the function component signature not accepts two arguments, the props object and the React ref that is being forwarded, and that the useImperativeHandle hook references the forwarded ref.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda