0

I have two .map functions used for displaying the contents of two SQL tables I have. This is achieved through mapping an array.

I have noticed performance issues when I recently added the second map. I would like to know a way of improving the performance as both of these tables will eventually contain more data and the issue will only increase.

Perhaps a method of rendering the arrays entirely only once instead of repeating the map function.

Currently each table contains on row with a varchar with the products table containing an image src

Heres the file

import React, {useState, useEffect} from 'react';
import axios from 'axios';
import Helmet from 'react-helmet';

export default function Database() {
    const [userRows, setUserRows] = useState([]);
    const [productRows, setProductRows] = useState([]);
    const [data, setData] = useState('');

    useEffect(() => {
        axios.get('/users/get')
            .then(res => {
                setUserRows(res.data);
            }).catch(err => {
            console.log(err);
        });

        axios.get('/products/get/')
        .then(res => {
            setProductRows(res.data);
        }).catch(err => {
        console.log(err);
        });
    });

    //Insert into database api request
    const insertRow = () => {
        axios.post('/users/insert', {
            row: data
        });
    };

    //Delete from database api request
    const deleteRow = () => {
        axios.delete(`/users/delete/${data}`);
    };

    return (
        <>
            <Helmet>
                <title>Title | Database</title>
            </Helmet>
            
            <input className="mt-60" type="text" onChange={(e) => {
                setData(e.target.value);
            }} />

            <button onClick={insertRow}>Submit</button>

            {userRows.map((row) => {
                return (
                    <div>
                        <p>{row.test}</p>
                        <button onClick={() => {deleteRow(row.test)}}>Delete</button>
                    </div>
                )
            })}

            {productRows.map((row) => {
                return (
                    <div>
                        <p>{row.name}</p>
                    </div>
                )
            })}
        </>
    );
};
Josh Haywood
  • 81
  • 10
  • 1
    Add empty array([]) as useEffect's dependencies. It means that your effect called only once after mount. Without it, it called whenever component re render. – Lee Jongseo Oct 09 '22 at 14:22

1 Answers1

0

useEffect should work once, you should use it like useEffect(()=> {},[]) you can add extra data to pages

How to implement pagination in React

korayaggul
  • 72
  • 5