0

I have a function in my react app that capitalized the first letter of a word or string that is fetched from an API:

  // Capitalize the first letter of the word/phrase
  const capitalize = (string) => {
    if (string) {
      return string
        .toLowerCase()
        .split(" ")
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");
    } else {
      return;
    }
  };

Note: string is the text that is being fetched from the API. I call the function like so:

capitalize(userInfo.address)

It works as expected but upon logging the results to the console, I realized that it is being run two to three times.

Sandbox: https://codesandbox.io/s/admiring-bose-2qr01j?file=/src/App.js

Is there a way to fix this?

Nima
  • 996
  • 2
  • 9
  • 37

2 Answers2

1

This might be caused by React Strict Mode. Check your index.js. By default React wraps your <App/> component with <React.StrictMode> which intentionally invokes the render method of your inner components two times.

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Just remove it to run functions only once.

root.render(
  <App />
);
0

It seems that the function is correct, but perhaps, when it is executed after a call to an external data source, an asynchronous call is being made (and possibly more than one), so the capitalize function is executed more than once .

Try to make the function run regardless of where you are calling from.

It could also be that you are executing the function from a code block that is executed more than once, because the function seems to be correct and does not have anything iterative.

  • The call to the API is done with Redux Thunk and I can see that it is being called once to get that data. The component that the `capitalize` function is being called from, is part of another parent component that gets rendered at first and then its children populate the UI. (Component Tree = App => Dashboard => Personal Info) – Nima May 27 '22 at 06:37