0

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.

Batman
  • 5,563
  • 18
  • 79
  • 155
  • Where is `onConfirm`? How do you call it? Please provide a reproducible example instead of snippets [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash Nov 24 '20 at 11:08
  • `onConfirm` is part of the `modalSettings` inside `handleDiscard`. – Batman Nov 24 '20 at 11:11
  • So whats the problem? `claim` is `null`, where you change it? – Dennis Vash Nov 24 '20 at 11:12
  • Yea, so when the app loads `claims: [data, data, data]` and there's a new prop `claim: {// selected object}` however, I just get the initial state back inside `onConfirm`. It doesn't show the current state, only the initial state. – Batman Nov 24 '20 at 11:15
  • Can you make a codesandbox or reproducible example? This code doesn't say much. – Dennis Vash Nov 24 '20 at 11:16

0 Answers0