What should we do if a item in scrum takes longer then expected?
Assuming that by item you mean story, at the end of the sprint you typically put it back in the product backlog (and likely plan it for the next iteration). The team scores zero points for it in the current iteration.
Another alternative, if the story is big enough, is to slice it vertically. For example, the story "product catalog search", can possibly be split in "search by category" and "full text search", but not in "search form" and "search results".
How can we avoid such situation in future?
There is no easy direct answer to this. In scrum you do sprint retrospectives every iteration, where you typically discuss these kinds of things with the team. There are many different possibilities:
- The team, or some team members, has a bad week
- Your team pipelines work items horizontally (e.g. backend->frontend->QA)
- The stories are too big by mistake
- The team "gold plates" the stories by adding extra work which is not strictly necessary for the completion of the story.
- The stories are very big in nature, you need longer sprints (unlikely)
- The team estimates stories imprecisely (incoherently)
- The project has a lot of tech debt/rotten code base and your velocity is too low
- You are not measuring and estimating your sprint capacity correctly (or at all).
etc. etc.