I am trying to find fibonacci sequence using state and a recursive action in vuex. Basically what I am trying here is rewrite this Javascript recursive function with vuex.
function fib(n) {
if (n < 2){
return n
}
return fib(n - 1) + fib (n - 2)
}
However, even if I am assigning the state to the action, the state's value never change. How can I make it work? I mean... I am struggling with this for a few days, so if you could give me some tips, or ideas, it would really helps.
Thanks. and this is my code below.
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store ({
state: {
number: 8
},
mutations: {
showTheNumber: (state) => {
return state.number
}
},
actions: {
findFibNum: ({ dispatch, commit, state }) => {
if (state.number < 2) {
return state.number
} else {
dispatch('findFibNum', state.number - 1) + dispatch('findFibNum', state.number - 2)
}
return commit('showTheNumber')// I am not sure if it is redundant
}
}
and this is how I am calling and showing the value of store in the component.
<template>
<div>
<input @input="addUserInput"></input>
<p>Counter is: {{ counter }}</p>
</div>
</template>
<script>
export default {
methods: {
addUserInput () {
this.$store.dispatch('findFibNum')
}
},
computed: {
counter(){
return this.$store.state.number;
}
}
}
</script>