0

I have created a reusable component that is used by multiple consumer templates. And the templates are passing props with different values. template-A is passing propA = { name: "John"} whereas template-B isn't passing propA. And the component makes an API call in the useEffect method based on the passed propA where it sets a default value for propA as an empty object. the problem here is the template-B is invoking the API call twice. I assume it's causing because, since template-B isn't passing propA the value of propA changes from undefined to default empty object. How would you handle this scenario to avoid multiple API calls?

Component

const defaultVal = {};
const Component = ({ propA = defaultVal}) => {
  useEffect(() => {
    fetch("url").then((data) => {
      setData(data)
    })
  }, [propA])
};

Template - A

<Component propA = {{ name: "John"}} />

Template - B

<Component />

Any helps would be appreciated, Thanks in advance!

Vivekraj K R
  • 2,418
  • 2
  • 19
  • 38
  • 2
    Given how you defined ``, `propA` will never be `undefined`. So your assumption that the problem occurs because it switches from *undefined* to the *default* value cannot be correct. There must be some other source for the problem. Are you rendering your app in strict mode maybe? – Yoshi Aug 04 '21 at 12:10
  • @Yoshi Ok, so what would be the value of propA if I didn't pass it. – Vivekraj K R Aug 04 '21 at 12:13
  • 1
    The current value of `defaultVal`. – Yoshi Aug 04 '21 at 12:14
  • Mmm, that's true. – Vivekraj K R Aug 04 '21 at 12:23
  • A question: but is really necessary to have `propA` in `useEffect` deps list? I can't see any dependencies in useEffect's code (but maybe you wrote just an example, the code is more complex...) – Giovanni Esposito Aug 04 '21 at 12:35
  • That's a great question. I use prettier for code formatting and prettier has strict rules. It forcing me to add these props to the dependency array. – Vivekraj K R Aug 04 '21 at 13:55

0 Answers0