MattB
7 months ago
1226
2
Vue

Issue editing items in Vue table

Posted 7 months ago by MattB

I have a table with the ability to add new items and edit existing ones (with the edit button being next to each entry). I have an issue with it whereby if you were to add a new item, NOT refresh the page, but then go to edit the item, it will edit it on Vue but not pass the edit back to the database. When you go to edit an item, the PUT URL returns a 404 error. If however, you refresh the page after adding an item, you can edit it perfectly fine. Any ideas what I've done wrong, or maybe forgotten to add?

Component:

<template>
    <v-data-table
        :headers="headers"
        :items="questions"
        sort-by="question"
        class="elevation-1"
    >
        <template v-slot:top>
            <v-toolbar flat color="white">
                <v-toolbar-title>FAQs</v-toolbar-title>
                <v-spacer></v-spacer>
                <v-dialog v-model="dialog" max-width="700px">
                    <template v-slot:activator="{ on }">
                        <v-btn color="primary" dark class="mb-2" v-on="on">New Item</v-btn>
                    </template>
                    <v-card>
                        <v-card-title>
                            <span class="headline">{{ formTitle }}</span>
                        </v-card-title>

                        <v-card-text>
                            <v-container>
                                <v-row>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-textarea v-model="editedItem.question" label="Question"></v-textarea>
                                    </v-col>
                                    <v-col cols="12" sm="6" md="6">
                                        <v-textarea v-model="editedItem.answer" label="Answer"></v-textarea>
                                    </v-col>
                                </v-row>
                            </v-container>
                        </v-card-text>

                        <v-card-actions>
                            <v-spacer></v-spacer>
                            <v-btn color="blue darken-1" text @click="close">Cancel</v-btn>
                            <v-btn color="blue darken-1" text @click="saveToServer">Save</v-btn>
                        </v-card-actions>
                    </v-card>
                </v-dialog>
            </v-toolbar>
        </template>
        <template v-slot:item.action="{ item }">
            <v-icon
                small
                class="mr-2"
                @click="editItem(item)"
            >
                mdi-square-edit-outline
            </v-icon>
            <v-icon
                small
                @click="deleteItem(item)"
            >
                mdi-delete
            </v-icon>
        </template>
        <template v-slot:no-data>
            <v-btn color="primary" @click="initialize">Reset</v-btn>
        </template>
    </v-data-table>
</template>

<script>
    export default {
        data: () => ({
            dialog: false,
            headers: [
                {
                    text: 'Question',
                    align: 'left',
                    sortable: true,
                    value: 'question',
                    width: '25%'
                },
                { text: 'Answer', value: 'answer', width: '55%' },
                { text: 'Actions', value: 'action', sortable: false, width: '20%' },
            ],
            questions: [],
            editedIndex: -1,
            editedItem: {
                question: '',
                answer: ''
            },
            defaultItem: {
                question: '',
                answer: ''
            },
        }),

        computed: {
            formTitle () {
                return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
            },
        },

        watch: {
            dialog (val) {
                val || this.close()
            },
        },

        created () {
            this.initialize();
            this.loadUsers();
        },

        methods: {
            initialize () {
                this.questions = []
            },
            loadUsers(){
                if (axios == null) {
                    return;
                }
                axios.get('/api/faq').then(res=>{
                    if(res.status === 200){
                        this.questions=res.data;
                    }
                }).catch(err=>{
                    console.log(err);
                });
            },

            editItem (item) {
                this.editedIndex = this.questions.indexOf(item);
                this.editedItem = Object.assign({}, item);
                this.dialog = true
            },

            deleteItem (item) {
                const index = this.questions.indexOf(item);
                confirm('Are you sure you want to delete this item?') && this.questions.splice(index, 1)
            },

            close () {
                this.dialog = false;
                setTimeout(() => {
                    this.editedItem = Object.assign({}, this.defaultItem);
                    this.editedIndex = -1
                }, 300)
            },

            saveToServer () {
                if (this.editedIndex > -1) {
                    // Edit item
                    Object.assign(this.questions[this.editedIndex], this.editedItem);
                    axios.put('/api/faq/' + this.questions[this.editedIndex].id, this.editedItem).then(function (response) {
                        console.log(response);
                    })
                        .catch(function (error) {
                            console.log(error);
                        });
                } else {
                    //New item
                    this.questions.push(this.editedItem);
                    axios.post('/api/faq', this.editedItem).then(function (response) {
                        console.log('Before');
                        this.id = response.id;
                        console.log('After');
                        Object.assign(this.questions[this.editedIndex], this);
                        console.log(response);
                    })
                        .catch(function (error) {
                            console.log(error);
                        });
                }

                this.close()
            },
        },
    }
</script>

Store controller:

public function store(Request $request)
    {
        $bodyContent = $request->getContent();
        Storage::disk('local')->put('APIdump.txt', $bodyContent);
        $id = faq::insertGetId($request->all());
        return Response:: json([
            'status' => 'ok',
            'id' => $id,
        ], 200);
    }

Update controller:

public function update(Request $request, $id)
    {
        faq::findOrFail($id)->update($request->all());
        return response(['message' => 'Success']);

    }

Please sign in or create an account to participate in this conversation.