0

I'm building a React component that utilizes a third party vanilla Javascript library that's forcing a somewhat unique situation. The third party library renders a component as a child of the div with id "3rdparty-container". My user provides some inputs in that 3rd party UI and then, when successful, my "put" callback is invoked. That callback invokes my back end API which reaches out to the third party service's API to retrieve data generated by the activity my user performed in the third party UI that's embedded in my app. My "put" callback also updates the stateObj in my DataContext. I can see this is all working because other components that consume the same context are immediately rerendered with the new data.

However, when this flow occurs, I expect stateObj logged to the console after put() is called to be different than the version logged prior to the put(). Instead, I'm seeing exactly the same data logged in both cases. I'm guessing this is because the stateObj object in this component isn't being updated even though the underlying DataContext is.

How can I get the updated stateObj data (following put()) inside my launch3rdPartyUI function which is called inside useEffect?

import { useEffect } from "react";

const MyComponent = ({ token }) => {

    const { stateObj } = useDataContext();
    const { put } = stateObj;

    const thirdPartyUrl = process.env.thirdPartyUrl;

    const launch3rdPartyUI = () => {
        const params = {
            accessToken: `Bearer ${token}`,
            thirdPartyUrl: thirdPartyUrl,
            onSuccess: function (data) {
                console.log("STATEOBJ BEFORE UPDATE: ", stateObj)
                put().then(() => console.log("STATEOBJ AFTER UPDATE: ", stateObj)); //put is an async function that calls my back end API to retrieves data from the third party service and updates the stateobj object in my DataContext.
            }
        };

        setTimeout(() => {
            window.thirdPartyService.open(params, "3rdparty-container");
        }, 0.05);
    };

    useEffect(() => {
        launch3rdPartyUI();
        // eslint-disable-next-line
    }, []);

    return <div id="3rdparty-container" />;

};

export default MyComponent;```
Matt Frei
  • 329
  • 1
  • 3
  • 11

0 Answers0