Vue

by darkylmnx

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<div id="app">
  <h2>Quizz</h2>
  <ol>
    <li v-for="q in questions">
      <p>{{ q.text }}</p>
      <p>
        <label v-for="(a, idx) in q.answers" :for="q.id + '-' + idx">
          {{ a }}
          <input type="radio" @change="onSelect(q, a)" :name="q.id" :id="q.id + '-' + idx" />
        </label>
      </p>
    </li>
  </ol>
  
  <button @click="submit">submit all</button>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

label {
  display: inline-block;
  padding: 4px 6px;
  background: lightpink;
}

Vue

// fake use of the session that you generatre or got from the server
var user = {
	id: 145214
}

new Vue({
  el: "#app",
  data: {
    questions: [
      { id: 1, text: "Learn JavaScript", answers: ['yes', 'no'] },
      { id: 2, text: "Learn Vue", answers: ['yes', 'no', 'maybe'] },
      { id: 3, text: "Play around in JSFiddle", answers: ['hell yeah', 'nope'] },
      { id: 4, text: "Build something awesome", answers: ['sure !'] }
    ]
  },
  methods: {
  	submit() {
    	// validate all previous sent answers
      // eventually, get all local answers left in the localstorage with a loop and a condition on the each key
    	axios.post('/my-api/quizz/finalize', {
      	uid: user.id
      })
    },
  
  	onSelect: function(q, a){
    	console.log(q.id, a)
    
    	// stringify answer, if the answer is an object
      // but here it's a string so no need
      // save the current answer with a key of it's id
      // in case connection is lost
    	localStorage.setItem('question-' + q.id, a)
      
      // save to server
      axios.post('/my-api/quizz/drafts', {
      	uid: user.id,
        qui: q.id,
        answer: a
      })
      .then(() => {
      	// if everything went well, delete from local
        localStorage.removeItem('question-' + q.id)
      })
      .catch(() => {
      	// something failed, (no network or anything else)
        // handle it
      })
      .then(() => {
      	// finally, wether it went well or not, lets show the local storage
      	// instead of using another then after the cat, use a "finally"
        console.log(localStorage)
      })
    }
  }
})