1

There is a simple component with the output of records to a table that reads data from the server (GET) and adds (POST) a record to it at the click of a button.

<template>
    <div>
        <table class="table" v-if="companies && companies.length">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">ID</th>
                    <th scope="col">NAME</th>
                    <th scope="col">INN</th>
                </tr>
            </thead>


            <tbody v-for="(company, index) of companies" v-bind:key="company.id">
                <tr>
                    <th>{{ index + 1 }}</th>
                    <th>{{ company.id }}</th>
                    <th>{{ company.name }}</th>
                    <th>{{ company.inn }}</th>
                </tr>
            </tbody>
        </table>

        <button v-on:click="addCompany">addCompany</button>

        <ul v-if="errors && errors.length">
            <li v-for="error of errors" v-bind:key="error.id">
                {{ error.message }}
            </li>
        </ul>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    name: 'ksoCompanyTable',
    data() {
        return {
            companies: [],
            errors: [],
            render: 1
        }
    },
    methods: {
        async addCompany() {
            axios.post('api/company', {
                name: 'JJJ Apple',
                inn: '000000999'
            })
                .then(response => {
                    /** 
                     *? for update component on the page
                     **/
                    this.companies.push(
                        {
                            'id': response.data.insertId,
                            'name': JSON.parse(response.config.data).name,
                            'inn': JSON.parse(response.config.data).inn
                        });
                })
                .catch(function (error) {
                    console.log(error);
                });
        },
    },
    mounted() {
        axios.get('/api/company')
            .then(response => {
                this.companies = response.data
            })
            .catch(e => {
                this.errors.push(e)
            })
    }
}
</script>

Here is the code of the endpoints handler on the server side.

const express = require('express');
const { Router, response } = require('express');
const router = Router();
const mysql = require('mysql2');


router.use(express.json());

const connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'mevn-invoice',
});

router.get('/company', async (req, res) => {
    try {
        await connection.execute(
            'SELECT * FROM `companies`',
            function (err, results) {
                if (err) console.log(err);
                return res.status(200).json(results);
            });
    } catch (e) {
        res.status(500).json({ message: 'Error on Company route' });
    }
});

router.post('/company', async (req, res) => {
    try {
        const { name, inn } = req.body;
        console.log(req.body);
        let sql = 'INSERT INTO companies (name, inn) VALUES (?, ?)';

        await connection.execute(sql, [name, inn], function (err, results, next) {
            if (err) console.log(err);
            //return res.status(200).json({message: '1 record added.'});
            return res.status(200).json(results);
        });

    } catch (e) {
        res.status(500).json({ message: 'Error on Company/POST route' });
    }

});

module.exports = router;

Question.

After adding a record, i need to update (without reloading the page, of course) the table component.

In my addCompany() method, everything looks complicated somehow. Is this a "crooked" solution?

Can you point in the right direction and tell me how "these things are being done correctly"?

Very confusing is a similar code that I gave birth to but it works )

.then(response => {
                    /** 
                     *? for update component on the page
                     **/
                    this.companies.push(
                        {
                            'id': response.data.insertId,
                            'name': JSON.parse(response.config.data).name,
                            'inn': JSON.parse(response.config.data).inn
                        });
                })
kissu
  • 40,416
  • 14
  • 65
  • 133
Shoshin
  • 23
  • 5

1 Answers1

1

If you remove some line jumps and space + use the async/await syntax, you can make it look cleaner but if it works, it's totally fine: it's not bad looking code. It's doing the things in a simple manner.

You could also setup ESlint + Prettier if you want some fast linting + formatting: https://stackoverflow.com/a/68880413/8816585

You could also throw back all the new records and save the whole array on your frontend but this is less optimal regarding network bandwidth.

kissu
  • 40,416
  • 14
  • 65
  • 133