skip to Main Content

Similar to other questions not not quite the same: I have a variable assignment which involves calling a function that takes a significant amount of time to run, and I want to trigger a function after that assignment finishes. (The function I want to trigger is a React setState function, if relevant).

The line of code currently looks something like this:

const data = handler.get(endpoint).then(res => setMyState("finished getting endpoint"))

Unfortunately, this seems to be assigning the result of the ".then()" segment to "data" instead of the "handler.get" segment.

Is there a way I can trigger a ‘.then()’ off of a variable assignment while capturing the value of the left half of the function chain?

2

Answers


  1. You can use a useEffect hook with the variable you assign as a dependency

    useEffect(() => {
      // check if 'data' isn't empty
      setMyState("finished getting endpoint");
    }, [data]);
    
    Login or Signup to reply.
  2. It sounds like you want Promise.prototype.finally(). This will run after the promise resolves or rejects but it will not effect the resolved value.

    // mocks
    const handler={get:()=>new Promise((r)=>{setTimeout(r,200,"handler resolved value");})};
    const setMyState=(v)=>{console.log("[setMyState]",v);};
    const endpoint = "https://example.com/";
    
    const dataPromise = handler.get(endpoint)
      .finally(() => {
        setMyState("finished getting endpoint");
      });
      
    // you can still reference the resolved value
    dataPromise.then((res) => {
      console.log("[dataPromise]", res);
    });

    A simpler option is to use async / await syntax instead

    const getData = async () => {
      const data = await handler.get(endpoint);
      setMyState("finished getting endpoint");
      return data;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search