From a variety of texts I've read, both growing up in the South and now, it seems that it took until the mid-20th century for a general agreement on the facts of the matter. Yet Bruce Levine's extremely readable The Fall of the House of Dixie cites page after page of primary source documents (from newspapers, to diaries, to the text of the Confederate constitution itself) that clearly and loudly trumpet the defense of slavery and its attendant way of life as the cause of the war.
It seems strange that people so much closer to the time of the publication of these primary source documents could have arrived at a place so much further from the truth than today's scholars. Was there a significant contingent of scholars who saw slavery as the cause of the war but were shouted down, or did it really take nearly a century for that fact to be agreed upon?
There are quite a few studies on the memory of the Civil War, but my favorite is David Blight's Race and Reunion. In it, he lays out two reason for the distorted nature of public memory of the Civil War.
Firstly, Confederate histories of the war beat Union ones to the market. Edward A. Pollard set the tone with his 1866 book, The Lost Cause: A New Southern History of the War of the Confederates. Former Confederate general Jubal Early became the head of the Southern Historical Society after the war, and published a steady stream of articles pushing the idea that defending states' rights were the Confederates' primary aim. This is to say that ex-Confederates launched a very specific campaign on the field of history to secure their narrative.
The other reason is that reconciliation worked for white Northerners. By 1876, both the centennial of the Declaration of Independence and the year of a presidential election, the white North was tired of sending soldiers and money to fight a war that had formally ended eleven years earlier. Ending Reconstruction and moving forward all under one flag allowed the nation to put the trauma of the war behind them - at the expense of black lives and black liberty. That was an offer the white North was willing to take.