2

I converted my class-based component to a functional component and thought I had the conversion of the componentDidUpdate method correct, but my linter is complaining, so I could use some clarification on what I'm getting wrong.

This is my componentDidUpdate function on a class-based component:

componentDidUpdate(prevProps) {
  if (
    prevProps.hasUnlockBeenClicked !== this.props.hasUnlockBeenClicked &&
    this.props.hasUnlockBeenClicked &&
    !this.props.startAt
  ) {
    this.saveInitialSession();
  }
}

saveInitialSession = () => {
  const { setSessionProperties, agentId, customerId, customerName } = this.props;
  setSessionProperties({
    agentId,
    customerId,
    customerName,
    startAt: moment().format(),
  });
}

This is what I'm attempting to change it to using useEffect() on a functional component:

const saveInitialSession = () => {
  setSessionProperties({
    agentId,
    customerId,
    customerName,
    startAt: moment().format(),
  });
};

useEffect(() => {
  if (hasUnlockBeenClicked && !startAt) {
    saveInitialSession();
  }
}, [hasUnlockBeenClicked]);

Eslint is telling me that the dependency array needs to include startAt and saveInitialSession, which doesn't make any sense to me. I only want it to run if the hasUnlockBeenClicked has been changed.

zeckdude
  • 15,877
  • 43
  • 139
  • 187
  • Are you using VS Code? – Chris Ngo Jul 10 '19 at 06:28
  • Yes I sure am!! – zeckdude Jul 10 '19 at 06:29
  • after the if-block in your `useEffect` add the following: `eslint-disable-next-line react-hooks/exhaustive-deps` – Chris Ngo Jul 10 '19 at 06:30
  • Isn’t that eslint rule there for a reason? Can you tell me why I would just want to turn it off? – zeckdude Jul 10 '19 at 06:31
  • Looks like valid warning. You should add `startAt` and `saveInitialSession` in the dependency array. Check for explanation [here](https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies). Search for the example expelling about `ProductPage` and how `fetchProduct` `productId` should go into depedencies. – Panther Jul 10 '19 at 06:33
  • You can see more :https://github.com/facebook/react/issues/14920 – Ryan Nghiem Jul 10 '19 at 06:34
  • Panther, so if startAt changes, won’t it run the function? I only want the anonymous function to run if has UnlockBeenClicked. – zeckdude Jul 10 '19 at 06:38
  • Possible duplicate of https://stackoverflow.com/questions/55840294/how-do-i-fix-missing-dependency-in-react-hook-useeffect/55854902#55854902 – Shubham Khatri Jul 10 '19 at 07:01
  • is `setSessionProperties` a setter from `useState()`? If yes, I have workaround for you on this thing. – skyboyer Jul 10 '19 at 07:26
  • `setSessionProperties` is a redux action creator – zeckdude Jul 10 '19 at 16:39

0 Answers0