V
V
venom992021-07-15 16:54:22
Vue.js
venom99, 2021-07-15 16:54:22

How to overwrite the data in the state, on those that come from the backend?

Data from the server comes in JSON format. Initially, the state has empty values, and I don’t understand how to overwrite them with those that come from the server. Now data from the server is simply added to the state, instead of overwriting the old values.
PS For clarity, I displayed what is displayed on the

index.js screen

import index, {createStore} from "vuex";
import axios from "axios";
import router from "@/router/router";

export default createStore({
    state: () => ({
        data: {

                id: 0,
                username: "",
                password: "",
                status: 0,

        },
}),
    getters: {
        new_username(state) {
            return state
        },
    },
    mutations: {
        setlogin(state,username) {
            state.username = username;
        },
        setpassword(state, password){
             state.password = password;
        },

    },
    actions: {
        async login() {
            try {
                const {id, username, password, status} = this.state;
                const {data} = await axios.post('http://127.0.0.1:5000/login', {
                    id,
                    username,
                    password,
                    status
                })
                const mydata = (JSON.parse(data))
                if (mydata[3] === 1) {

                    return router.push('/main')
                }
                if (mydata[3] === 2) {
                    return router.push('/teacher')
                }
            } catch (e) {
                return alert('Неверный логин или пароль');
            }
        }

    },
})

60f03dc3e3dac796466265.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2021-07-15
@venom99

You are modifying the root object in the mutation. So you wrote something like this

const state = {data: {user: ''}}
state.user = '...' // <-- Изменяете не то поле

You need to modify the subobjectdata
const state = {data: {user: ''}}
state.data.user = '...' // <--

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question