I have an array of names to which I add elements like this within a function:
const [names, setNames] =useState([])
for (const file of allFiles){
setNames([...names, String(file)])
}
return (
{names && names.map((name) => (
<p>{name}</p>
))}
)
What puzzles me is that what gets printed to the website is every file name, one after the other on the same line. So every new name replaces the last until we reach the last name, and the only name that appears is the last name. However, I’d like to display every name on a new line. How can I achieve this?
2
Answers
I’m not sure how you’re structuring your code, but you need to set the state
names
only once at the end after your loop / your logic with files using theallFiles
array.It’s as simple as doing
setNames(allFiles)
for the state to represent all the files in an array.Also if you need to execute some code whenever the state that represents the files changes, or whenever the page is initially loaded, I suggest you look into the
useEffect
hook.as mentioned in other answers you might want to look at something like this: