Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

javascript - Cannot get store states with getters in Vuex with promise then

Since I want to check if the channel route they enter need PIN code or not, I use router.beforeEach as below:

router.beforeEach((to, from, next) => {  
  if(to.path == '/') {
    next();
  }else {                
    store.dispatch('checkChannelhasPin', to.params.id).then(()=>{
    console.log(store.getters);
    console.log(store.getters.ispin);
    setTimeout(() => {
      console.log(store.getters.ispin);
     }, 500);
   }) 
  }
}

As console.log, I have three results:

enter image description here

The problem is that, I'm unable to get stateispin after checking 'checkChannelhasPin'.

The action:

import axios from 'axios';
import setChannelAuthToken from '../../utils/setChannelAuthToken';
import {
  CHECK_CHANNEL_HASPIN
} from '../typeName';

const state = {
  ispin: true,      
}

const getters = {  
  ispin: (state) => state.ispin
};

const actions = {      
  async checkChannelhasPin({commit}, params) {    
    axios.post(
      window.home+'/json/channel/checkAuth',
      {
        channel_id:params
      }
    ).then((response) => {      
      let payload = response.data.ispin;
      commit(CHECK_CHANNEL_HASPIN, payload); 
    }).catch( (error) => {
      console.log(error);
    });
  }
}


const mutations = {
  CHECK_CHANNEL_HASPIN: (state, payload) => (state.ispin = payload)
};

export default {
  state,
  getters,
  actions,
  mutations
};

Can you suggest me? Thank you very much.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to return the promise from the action:

checkChannelhasPin({commit}, params) {    
  return axios.post(
    window.home+'/json/channel/checkAuth',
    {
      channel_id:params
    }
  ).then((response) => {      
    let payload = response.data.ispin;
    commit(CHECK_CHANNEL_HASPIN, payload); 
  }).catch( (error) => {
    console.log(error);
  });
}

Or, if you used async/await syntax you could do this:

async checkChannelhasPin({commit}, params) {
  try {
    const response = await axios.post(
      window.home+'/json/channel/checkAuth',
      {
        channel_id:params
      }
    )
    let payload = response.data.ispin;
    commit(CHECK_CHANNEL_HASPIN, payload); 
  } catch(error) {
    console.log(error);
  }
}

When you use .then you have to explicitly return the promise. When you use async/await, you don't. You were using the async keyword, but using .then instead of await.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...