M
M
Maxim js2021-04-09 16:58:14
Vue.js
Maxim js, 2021-04-09 16:58:14

How to correctly output data from API in Vuex 4?

Tell me what am I doing wrong?

import {createStore} from 'vuex'
const axios = require('axios');

const baseURL = 'https://swapi.dev/api/people/';

export default createStore({
    state: {
        characters: [],
    },
    mutations: {
        SET_CHARACTERS: (state, payload) => {
            state.characters = payload;
        },
    },
    actions: {
        GET_CHARACTERS: async (context) => {
            let data = await axios.get(baseURL);
            context.commit('SET_CHARACTERS', data)
        }
    },
    getters: {
        CHARACTERS: state => {
            return state.characters;
        }
    },
    modules: {}
})



{{ $store.state.characters}}





<template>
    <div class="card">
        <div>{{ $store.state.characters }}</div>
    </div>
</template>

<script>
import {mapGetters} from 'vuex';
export default {
    computed: {
        ...mapGetters(['CHARACTERS'])
    }
}
</script>

<style lang="scss" src="./card.scss">

</style>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-04-09
@winers

Where is the action call GET_CHARACTERS? I do not see. We must add.

let data = await axios.get(baseURL);
context.commit('SET_CHARACTERS', data)

Here you pass the entire response object to the mutation - not only the data, but also the status, headers, etc. Also, based on the default value of characters, you want an array, and what is returned is an object containing that array as the results property. So let it be
const response = await axios.get(baseURL);
context.commit('SET_CHARACTERS', response.data.results);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question