Can somebody explain why the id generated by the function generateId in utilities.js file in Passing Thoughts project gets incremented more that one ? Even if I remove the result variable and let only newId, still it gets incremented weirdly ?
It’s like this function gets called more than once. But where, cuz I don’t see where
Please post a link to the lesson and your code. Please make sure that your code is properly formatted.
Here is the link to Codecademy passing thoughts project:
If you look at files, in utilities.js are two functions that are exported. Then they are imported in App.js and called when thoughts array is initialised with setter setThoughts when using useState. So this is one call to them and makes them increment ?
Then they are imported in AddThoughtForm.js and called when new thought object is created. I think they increment again ?
If you look at react developer tools, you will see that id increments weird. First starts at 2, and then increments from 7 to 7.
Why is that ? They increment when they got called in the situations I mentioned above ?
utilities.js
export function getNewExpirationTime() {
return Date.now() + 15 * 1000;
}
let nextId = 0
export function generateId() {
const result = nextId;
nextId += 1;
return result;
}
App.js
import { useState } from "react";
import AddThoughtForm from "./components/AddThoughtForm";
import Thought from "./components/Thought";
import { generateId, getNewExpirationTime } from "./utilities";
function App() {
const [thoughts, setThoughts] = useState(
[ {
id: generateId(),
text: 'This is a place for your passing thoughts.',
expiresAt: getNewExpirationTime(),
},
{
id: generateId(),
text: "They'll be removed after 15 seconds.",
expiresAt: getNewExpirationTime(),
},]
)
const addThought = (thought) => {
setThoughts(prev => [thought, ...prev])
}
const removeThought = (thoughtIdToremove) => {
setThoughts((thoughts) => thoughts.filter(t => t.id !== thoughtIdToremove))
}
return (
<div className="App">
<header>
<h1>Passing Thoughts</h1>
</header>
<main>
<AddThoughtForm addThought={addThought}/>
<ul className="thoughts">
{thoughts.map( (thought) => (
<Thought removeThought={removeThought} key={thought.id} thought={thought}/>
))}
</ul>
</main>
</div>
);
}
export default App;
AddThoughtForm.js
nextId in utilities is incremented on each call of generateId.
generateId is called twice initially, if you have two initial thoughts in thoughts state. Each time you add a thought, generateId is called three times. Once for the added thought and once for each initial thought.
Each time a thought is removed, generateId is called twice – once for each initial thought. Even if the initial thoughts have long been removed.
From the react docs:
When you call
setState()
, React merges the object you provide into the current state.
I cannot observe that in my app.