In Hamlet, why does Hamlet attend the fencing competition when he knows his life is in danger?
You obviously need to look at Act V scene 2 to find the answer to this question. After both Osric and the Lord have entered to tell Hamlet about the impending fencing match with Laertes, Hamlet says to Horatio that in spite of all the practice he has been doing, he still has an odd premonition that something is not right about it, as he tells Horatio "how ill all's here about my heart."
However, when Horatio gives him the opportunity to get out of fighting the duel, Hamlet disagrees, giving the following speech as his reason:
Not a whit, we defy augury; there is special providence in the fall of a sparrow. If it be now, 'tis not to come: if it be not to come, it will be now: if it be not now, yet it will come; the readiness is all, since no man has aught of what he leaves.
Note the tone of this speech, which seems to show almost defiance in the face of whatever fate can throw at us as humans. Hamlet, finally, seems to have reached a stage in the play where he is able to demonstrate radical acceptance of whatever happens, even if that means his death. Even in the death of a sparrow, there is "special providence," and it is clear that he has accepted his death is inevitable anyway, so in one sense it makes little difference if he dies now or later. At last we finally seem to be presented with a Hamlet who is at peace with himself and with his future. This is why he duels with Laertes in spite of his premonitions.
In Shakespeare's Hamlet, Hamlet does not know ahead of time that Claudius and Laertes have plotted his death in the final scene of the play.
Their murder plot is based on surprise. Laertes stashes a sword that is tipped with poison, and Claudius spikes a drink with poison. They hatch the plan in secret and carry it out so that Hamlet doesn't know until it is too late.
Hamlet finds out that the drink is poisoned when his mother falls ill and identifies Claudius as the culprit. He finds out the sword tip is poisoned when Laertes tells him. Hamlet's mother is killed and Hamlet is already pricked with the poison sword by the time Hamlet becomes aware of the plan.
Of course, had Hamlet known he may have gone to the sword fight anyway, figuring he could out wit and out fight his opposition. But that is pure speculation. Hamlet is trying to make peace with Laertes when he accepts the invitiation to the contest with Laertes.