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?
CodePudding user response:
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 />
);
CodePudding user response:
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.