As an undergraduate doing research, your primary goal is to learn and publishing is secondary. Of course, publishing your results and going through all the associated things for the first time is part of the learning. There is nothing fundamentally wrong with spending your undergraduate years rediscovering something. To bring up a particularly relevant example for today: Alan Turing was elected a fellow of King's College in 1935 (at the end of his undergrad) by proving the central limit theorem. He failed to notice that it was already proved in 1922. I am sure he learned a lot from it.
Of course, you have to be prepared to rediscover. If you are not it can be very discouraging. From a person experience, when I was an undergrad preparing my first first-author paper for submission I ended up finding previous work that had shown almost the same results 3 years prior. I had spent a lot of time rediscovering the ideas and writing my paper and it was a pretty devastating blow. My supervisor's words of encouragement: "Don't worry, at least we know we're on the right track".
He was right, and I was able to learn a lot from the experience (eventually leading to other publications). The particular paper in question sat in the back of my filesystem for a while, but I returned to it 2 years later with fresh eyes to discover that it was not as derivative as I had originally judged it and even this paper ended up being published (with some modifications) at a conference.
Another adviser takes the idea of rediscovery even further. When we move into new territory on a project, he will suggest some directions knowing that the relevant theorems have been proved already. He will tell me: "this result has been proven, but don't look it up, you will arrive at it on your own and then we will both be able to understand it better". This approach works very well in math-like fields since you have the advantage of knowing what you are going after as true, but still get to experience all the joy of (re-)discovery and the lessons you learn along the way. Something that is often not obvious from just reading somebody else's paper.
As an undergrad, don't worry about accidentally working on something that has been done. Concentrate on learning as much as you can!