Search code examples
apivue.jsstatestore

api call using userid


I need to make an api call to get recommendations for a user. This is my api url: http://URL/../../patients/USER ID/recommendations

My user Id is saved in my vuex store in the file "patient.module.js:

state: {
    id: null,
    email: null,
    password: null,
    location: [],
    specialty: [],
    attribute: [],
    language: [],
    gender: [],
    editUser: false,
  },
  getters: {
    getUserId(state) {
      return state.id;
    },
  },

My store structure looks like this: enter image description here

In my RecommendationView I try to display the json-response from my api call. Here I wrote the method to make the api call.

     methods: {
    getRecommendations() {
      this.id = this.$store.getters.getUserId;
      return http
        .get(`/patients/${id}/recommendations`)
        .then((response) => {
          this.recommendation = response.data;
          console.log(response);
        })
        .catch((error) => {
          console.log(
            "Ein Fehler beim User ist aufgetreten: " + error.response
          );
        });
    },
  },

Unfortunately, I receive this error: id' is not defined How can I get the patient id from the store and send it with my request? Thank you in advance!


Solution

  • You can use mapState in computed like this.

    <script>
      import {mapState} from "vuex";
    
    
    export default {
      computed: {
        ...mapState({
          user: state => state.patient
        })
      },
      data() {},
      methods: {
        getRecommendations() {
          this.id = this.user.id;
          return http
            .get(`/patients/${id}/recommendations`)
            .then((response) => {
              this.recommendation = response.data;
              console.log(response);
            })
            .catch((error) => {
              console.log(
                "Ein Fehler beim User ist aufgetreten: " + error.response
              );
            });
        },
      }
    } 
    </script>