Callback using old state when called

54 Views Asked by At

I have a modal where I pass in the onConfirm callback that triggers when user clicks the confirm button. The issue I'm seeing is that the state in this function is not the current state but the initial application state.

app.js

const discardClaim = async () => {
    try {
        // Showing undefined here?
        if (state.claim) { 
            await api.discard(state.claim.id);
        }
        // Close confirmation
        dispatch({ type: "CLOSE_DISCARD_MODAL" });
    } catch (error) {
        // handle error
    }
};

const handleDiscard = () => {
    // Set confirmation
    const modalSettings = {
        confirmTitle: "MyTitle",
        confirmMessage: "Are you sure?",
        onConfirm: discardClaim
    };

    dispatch({ type: "OPEN_DISCARD_MODAL", payload: discardModal });
};

useEffect(() => {
    if (state.handleDiscard === undefined) {
        dispatch({ type: "SET_HANDLERS", payload: { handleDiscard } });
    }
}, []);

Inside the ConfirmationModal.jsx I do:

const { confirmTitle, confirmMessage, onConfirm } = modalSettings;
<Button color="red" text={confirmButton} onClick={onConfirm} />

My state provider looks like this:

  const [state, dispatch] = useReducer<state, any>(reduce, {
    data: [],
    claim: null,
  });

When I try to call onConfirm inside the ConfirmationModal, I only get the initial state and now the latest state.

0

There are 0 best solutions below