It is no accident that this question been waiting to be answered for several weeks now. It is not easy to answer and there is need to respect the pain of those who have suffered loss. It can be presumptuous to tell someone the reasons God had for allowing bad things to happen to them.
Many miscarriages are the result of problems such as nondisjunction in which chromosome pairs don’t come apart correctly in the reproduction process. Whether it is this or some other reason, very often a miscarried baby could not have been born as a normal healthy child. By the very nature of nature, bad things must happen. Many insects produce such numerous offspring that if they all survived to maturity they would soon completely take over the world. A lion family cannot survive without meat, requiring the death of another animal. Sadly for people, tragic deaths and miscarriages occur. We all live within this beautiful but terrible world in which sad things must happen. We suffer from sickness, disappointment and death. This is the way that God has designed things. We, however, are a work in progress. We would not judge a building as a failure because it is untidy when builders are still working on it, leaving untidy builder’s refuse. Nor should we judge God as failing because his plan for the world is not yet complete. God is creating a world in which there will be no suffering. However God’s plan for this requires pain now:
John 16:21-22 When a woman is giving birth, she has sorrow because her hour has come, but when she has delivered the baby, she no longer remembers the anguish, for joy that a human being has been born into the world. (22) So also you have sorrow now, but I will see you again, and your hearts will rejoice, and no one will take your joy from you.
Jesus has assured us that God cares about those who are his followers.
Mat 10:29-31 Are not two sparrows sold for a penny? And not one of them will fall to the ground apart from your Father. (30) But even the hairs of your head are all numbered. (31) Fear not, therefore; you are of more value than many sparrows.
Note what Jesus does not say. Jesus does not say that we will not lose hairs, nor that sparrows do not fall to the ground. Unhappy things will happen to us. God controls events even if he does not micromanage them.
In an individual case I cannot say what, if any, purpose God had in a miscarried baby. However we can use unhappy things in our lives to focus on the good things that God will do for us if we rely on him.