With my (so far) published non-fiction, it was not a matter of writing a book first. Both came out of a course. I wrote them because it meant that the course content could be more widely available. It actually saved me time to write a book rather than teach everyone one-to-one.
With the fiction - the ideas came after prayer days even though I was not praying about anything related to writing. I think real life stories often spark off an idea too.