Home > database >  How to use ForLoop in React Js
How to use ForLoop in React Js

Time:01-16

When I fetch data from Elasticsearch database, it is Array[10]. But it only displays 1 Array value for me. How can I use 'for loop' to display all?

I have fetched data from Elasticsearch database and displayed it successfully. But please tell me how to display all the data

import React, { useEffect, useState, useRef} from "react";
import './pages/table.css'
import _, { forEach } from "lodash";

function JsonDataDisplay() {
    
    // Limit data per page
    const pageSize = 10;

    // Limit the num of Rows per Page
    const [paginatedDataVal, setpaginatedDataVal] = useState();
    const [currentPage, setcurrentPage] = useState(1);

    const [data, setData] = useState([]);
    const dataVal = useRef([]);


    // variable creation with useRef
    const id = useRef([]);
    const ignored = useRef([]);
    const index1 = useRef([]);
    const score = useRef([]);

    const ephemeral_id = useRef([]);
    const agentId = useRef([]);
    const agentName = useRef([]);
    const agentType = useRef([]);
    const agentVersion = useRef([]);

    // const hostArch = useRef([]);
    // const hostHostName = useRef([]);
    // const hostId = useRef([]);
    // const hostIp = useRef([]);
    // const hostMac = useRef([]);
    // const hostname = useRef([]);
    
    // const osBuild = useRef([]);
    // const osFamily = useRef([]);
    // const osKernel = useRef([]);
    // const osName = useRef([]);
    // const osPlatform = useRef([]);
    // const osType = useRef([]);
    // const osVersion = useRef([]);

    const baseEventType = useRef([]);
    const baseType = useRef([]);
    
    const childProcessCreationTime = useRef([]);
    const childProcessElevationType = useRef([]);
    const childProcessFlsVerdict = useRef([]);
    const childProcessId = useRef([]);
    const childProcessPid = useRef([]);
    const childProcessVerdict = useRef([]);

    const customerId = useRef([]);
    const deviceName = useRef([]);
    const endpointId = useRef([]);
    const eventType = useRef([]);

    const processCreationTime = useRef([]);
    const processFlsVerdict = useRef([]);
    const processId = useRef([]);
    const processPid = useRef([]);
    const processUserName = useRef([]);
    const processVerdict = useRef([]);

    const sessionUser = useRef([]);
    const time = useRef([]);
    const type = useRef([]);
    const version = useRef([]);

    const shardsFailed = useRef([]);
    const shardsSkipped = useRef([]);
    const shardsSuccessful = useRef([]);
    const shardsTotal = useRef([]);


    //   page Count data definition
        const pageCount = dataVal? Math.ceil(dataVal.length/pageSize) :0;
        // return null if page count is 1
        // if(pageCount === 1) return null;
        // storing all pages in array
        const pages = _.range(1, pageCount 1);

    // Pagination Event handler Hook
    const pagination=(pageNum)=>{
        setcurrentPage(pageNum);
      const startIndex = (pageNum-1) * pageSize;
      const paginatedDataVal = _(dataVal).slice(startIndex).take(pageSize).value();
      setpaginatedDataVal(paginatedDataVal);
    }


        // API data fetching
    const apiGet = () => {
        var myHeaders = new Headers();
        myHeaders.append("Authorization", "Basic *********************==");

        var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
        };

        
        const ur1 = 'https://192.168.1.3:9200/someServer Address'

        fetch(ur1, requestOptions) 
        .then(response => response.json())
        .then(result => {
            
            setData(result);
            dataVal.current = result;
            
            console.log(result);
            setpaginatedDataVal(_(result.data).slice(0).take(pageSize).value());

            // forEach
        
            // Variable assignment
            id.current = dataVal.current.hits.hits[1]._id;
            ignored.current = dataVal.current.hits.hits[1]._ignored;
            index1.current = dataVal.current.hits.hits[1]._index;
            score.current = dataVal.current.hits.hits[1]._score;
            
            ephemeral_id.current = dataVal.current.hits.hits[1]._source.agent.ephemeral_id;
            agentId.current = dataVal.current.hits.hits[1]._source.agent.id;
            agentName.current = dataVal.current.hits.hits[1]._source.agent.name;
            agentType.current = dataVal.current.hits.hits[1]._source.agent.type;
            agentVersion.current = dataVal.current.hits.hits[1]._source.agent.version;

            // hostArch.current = dataVal.current.hits.hits[1]._source.host.architecture;
            // hostHostName.current = dataVal.current.hits.hits[1]._source.host.hostname;
            // hostId.current = dataVal.current.hits.hits[1]._source.host.id;
            // hostIp.current = dataVal.current.hits.hits[1]._source.host.ip[7];
            // hostMac.current = dataVal.current.hits.hits[1]._source.host.mac;
            // hostname.current = dataVal.current.hits.hits[1]._source.host.name;
        
            // osBuild.current = dataVal.current.hits.hits[1]._source.host.os.build;
            // osFamily.current = dataVal.current.hits.hits[1]._source.host.os.family;
            // osKernel.current = dataVal.current.hits.hits[1]._source.host.os.kernel;
            // osName.current = dataVal.current.hits.hits[1]._source.host.os.name;
            // osPlatform.current = dataVal.current.hits.hits[1]._source.host.os.platform;
            // osType.current = dataVal.current.hits.hits[1]._source.host.os.type;
            // osVersion.current = dataVal.current.hits.hits[1]._source.host.os.version;

             baseEventType.current = dataVal.current.hits.hits[1]._source.parse.baseEventType;
             baseType.current = dataVal.current.hits.hits[1]._source.parse.baseType;
            
             childProcessCreationTime.current = dataVal.current.hits.hits[1]._source.parse.childProcess.creationTime;
             childProcessElevationType.current = dataVal.current.hits.hits[1]._source.parse.childProcess.elevationType;
             childProcessFlsVerdict.current = dataVal.current.hits.hits[1]._source.parse.childProcess.flsVerdict;
             childProcessId.current = dataVal.current.hits.hits[1]._source.parse.childProcess.id;
             childProcessPid.current = dataVal.current.hits.hits[1]._source.parse.childProcess.pid;
             childProcessVerdict.current = dataVal.current.hits.hits[1]._source.parse.childProcess.verdict;

             customerId.current = dataVal.current.hits.hits[1]._source.parse.customerId;
             deviceName.current = dataVal.current.hits.hits[1]._source.parse.deviceName;
             endpointId.current = dataVal.current.hits.hits[1]._source.parse.endpointId;
             eventType.current = dataVal.current.hits.hits[1]._source.parse.eventType;

             processCreationTime.current = dataVal.current.hits.hits[1]._source.parse.processes[1].creationTime;
             processFlsVerdict.current = dataVal.current.hits.hits[1]._source.parse.processes[1].flsVerdict;
             processId.current = dataVal.current.hits.hits[1]._source.parse.processes[1].id;
             processPid.current = dataVal.current.hits.hits[1]._source.parse.processes[1].pid;
             processUserName.current = dataVal.current.hits.hits[1]._source.parse.processes[1].userName;
             processVerdict.current = dataVal.current.hits.hits[1]._source.parse.processes[1].verdict;

             sessionUser.current = dataVal.current.hits.hits[1]._source.parse.sessionUser;
             time.current = dataVal.current.hits.hits[1]._source.parse.time;
             type.current = dataVal.current.hits.hits[1]._source.parse.type;
             version.current = dataVal.current.hits.hits[1]._source.parse.version;

             shardsFailed.current = dataVal.current._shards.failed;
             shardsSkipped.current = dataVal.current._shards.skipped;
             shardsSuccessful.current = dataVal.current._shards.successful;
             shardsTotal.current = dataVal.current._shards.total;
           
        })
        .catch(error => console.log('error', error));
    };

    // This used to call the function on page load 
            useEffect(() => {
                apiGet();
            }, []);


            // Search Props
            const [value, setValue] = useState('');
            const [dataSource, setDataSource] = useState(dataVal.current);
            const [tableFilter, setTableFilter] = useState([]);

            // Search function used to pass data into input tag onChange Property
                const filterData = (e) =>{
                    if(e.target.value !== ""){
                        setValue(e.target.value);

                        const filterTable = dataSource.filter(o=>Object.keys(o).some(k=>
                            String(o[k]).toLowerCase().includes(e.target.value.toLowerCase())
                            ));
                            setTableFilter([...filterTable])
                    }else{
                        setValue(e.target.value);
                        setDataSource([...dataSource])
                    }
                }       

    return (
        <>
        <div>
             {/* Searrch data from table */}
        <div className="input-group mb-3">
          <input type="text" className="form-control" 
          placeholder="Search..." 
          aria-label="Username" 
          aria-describedby="basic-addon1" 
          value={value}
          onChange={filterData}/>
         </div>
             
        <table className="table table-striped">
                <thead>
            <tr>
                
                {/* <-- Url 1 --> */}
                <th>ID</th>
                <th>Ignored</th>
                <th>Index</th>
                <th>Score</th>

                {/* Agent */}
                <th>Agent Ephemeral_id</th>
                <th>Agent Id</th>
                <th>Agent Name</th>
                <th>Agent Type</th>
                <th>Agent Version</th>

                {/* Host */}
                {/* <th>Host Architecture</th>
                <th>Host Hostname</th>
                <th>Host Id</th>
                <th>Host IP</th>
                <th>Host MAC</th>
                <th>Host Name</th> */}

                {/* Host OS */}
                {/* <th>OS Build</th>
                <th>OS Family</th>
                <th>OS Kernel</th>
                <th>OS Name</th>
                <th>OS Platform</th>
                <th>OS Type</th>
                <th>OS Version</th> */}

                {/* Parse */}
                <th>Base Event Type</th>
                <th>Base Type</th>

                {/* Child Processes */}
                <th>Child Process Cretion Time</th>
                <th>Child Process Elevation Type</th>
                <th>Child Process fls Verdict</th>
                <th>Child Process Id</th>
                <th>Child Process PID</th>
                <th>Child Process Verdict</th>

                <th>Customer Id</th>
                <th>Device Name</th>
                <th>Endpoint Id</th>
                <th>Event Type</th>

                {/* Processes [] */}
                <th>Process Cretion Time</th>
                <th>Process fls Verdict</th>
                <th>Process Id</th>
                <th>Process PID</th>
                <th>Process UserName</th>
                <th>Process Verdict</th>

                <th>Session User</th>
                <th>Time</th>
                <th>Type</th>
                <th>Version</th>

                {/* Shards */}
                <th>Shard Failed</th>
                <th>Shard Skipped</th>
                <th>Shard Success</th>
                <th>Shard Total</th>
                
            </tr>
                </thead>

            <tbody>

             <tr>
             
            <td><pre>{id.current}</pre></td>
            <td><pre>{ignored.current}</pre></td>
            <td><pre>{index1.current}</pre></td>
            <td><pre>{score.current}</pre></td>
            
            <td><pre>{ephemeral_id.current}</pre></td>
            <td><pre>{agentId.current}</pre></td>
            <td><pre>{agentName.current}</pre></td>
            <td><pre>{agentType.current}</pre></td>
            <td><pre>{agentVersion.current}</pre></td>
            

            {/* <td><pre>{hostArch.current}</pre></td>
            <td><pre>{hostHostname.current}</pre></td>
            <td><pre>{hostId.current}</pre></td>
            <td><pre>{hostIp.current}</pre></td>
            <td><pre>{hostMac.current}</pre></td>
            <td><pre>{hostname.current}</pre></td>
            
            <td><pre>{osBuild.current}</pre></td>
            <td><pre>{osFamily.current}</pre></td>
            <td><pre>{osKernel.current}</pre></td>
            <td><pre>{osName.current}</pre></td>
            <td><pre>{osPlatform.current}</pre></td>
            <td><pre>{osType.current}</pre></td>

            <td><pre>{JSON.stringify(osVersion.current, null, 2)}</pre></td> */}
            
            <td><pre>{baseEventType.current}</pre></td>
            <td><pre>{baseType.current}</pre></td>
            
            
            <td><pre>{childProcessCreationTime.current}</pre></td>
            <td><pre>{childProcessElevationType.current}</pre></td>
            <td><pre>{childProcessFlsVerdict.current}</pre></td>
            <td><pre>{childProcessId.current}</pre></td>
            <td><pre>{childProcessPid.current}</pre></td>
            <td><pre>{childProcessVerdict.current}</pre></td>
            
            <td><pre>{customerId.current}</pre></td>
            <td><pre>{deviceName.current}</pre></td>
            <td><pre>{endpointId.current}</pre></td>
            <td><pre>{eventType.current}</pre></td>
            
            
            <td><pre>{processCreationTime.current}</pre></td>
            <td><pre>{processFlsVerdict.current}</pre></td>
            <td><pre>{processId.current}</pre></td>
            <td><pre>{processPid.current}</pre></td>
            <td><pre>{processUserName.current}</pre></td>
            <td><pre>{processVerdict.current}</pre></td>
            
            <td><pre>{sessionUser.current}</pre></td>
            <td><pre>{time.current}</pre></td>
            <td><pre>{type.current}</pre></td>
            <td><pre>{version.current}</pre></td>
        

            <td><pre>{shardsFailed.current}</pre></td>
            <td><pre>{shardsSkipped.current}</pre></td>
            <td><pre>{shardsSuccessful.current}</pre></td>
            <td><pre>{shardsTotal.current}</pre></td>
            
              </tr> 

            </tbody>
        </table>

        {/* Pagination */}
        <nav className="d-flex justify-content-center">
                <ul className="pagination">
                     {/* lists of available page nums */}
                    {
                        pages.map((page) => (
                            <li className={
                                page ===currentPage? "page-item active" : "page-item"
                            } key={'id'}>
                                
                                <p className="page-link"
                                 onClick={()=>pagination(page)}
                                >{page}</p>

                            </li>
                        ))
                    }

                </ul>
        </nav>
        
        </div>

        </>
    );

}

export default JsonDataDisplay;

How can I use 'for loop' to display all?

CodePudding user response:

There are 2 issues from here:

  1. In your table:

After you fetch data from api, you save data to your state. Dont use too much useRef to save data if it not unique in render function ( useRef just use to reference 1 element in DOM ). Then use it to render one by one data in array with .... You can use array.map():

     <table className="table table-striped">
       <thead>
        <tr>
            
            {/* <-- Url 1 --> */}
            <th>ID</th>
            <th>Ignored</th>
            <th>Index</th>
            <th>Score</th>

            {/* Agent */}
            <th>Agent Ephemeral_id</th>
            <th>Agent Id</th>
            <th>Agent Name</th>
            <th>Agent Type</th>
            <th>Agent Version</th>

            {/* Host */}
            {/* <th>Host Architecture</th>
            <th>Host Hostname</th>
            <th>Host Id</th>
            <th>Host IP</th>
            <th>Host MAC</th>
            <th>Host Name</th> */}

            {/* Host OS */}
            {/* <th>OS Build</th>
            <th>OS Family</th>
            <th>OS Kernel</th>
            <th>OS Name</th>
            <th>OS Platform</th>
            <th>OS Type</th>
            <th>OS Version</th> */}

            {/* Parse */}
            <th>Base Event Type</th>
            <th>Base Type</th>

            {/* Child Processes */}
            <th>Child Process Cretion Time</th>
            <th>Child Process Elevation Type</th>
            <th>Child Process fls Verdict</th>
            <th>Child Process Id</th>
            <th>Child Process PID</th>
            <th>Child Process Verdict</th>

            <th>Customer Id</th>
            <th>Device Name</th>
            <th>Endpoint Id</th>
            <th>Event Type</th>

            {/* Processes [] */}
            <th>Process Cretion Time</th>
            <th>Process fls Verdict</th>
            <th>Process Id</th>
            <th>Process PID</th>
            <th>Process UserName</th>
            <th>Process Verdict</th>

            <th>Session User</th>
            <th>Time</th>
            <th>Type</th>
            <th>Version</th>

            {/* Shards */}
            <th>Shard Failed</th>
            <th>Shard Skipped</th>
            <th>Shard Success</th>
            <th>Shard Total</th>
            
        </tr>
            </thead>

        <tbody>
        { data && data.map((index, item)=> 
           <tr key={index}>
         
        <td><pre>{item.id}</pre></td>
        <td><pre>{item.ignored}</pre></td>
        <td><pre>{item.index1}</pre></td>
        <td><pre>{item.score}</pre></td>
        
        <td><pre>{item.ephemeral_id}</pre></td>
        <td><pre>{item.agentId}</pre></td>
        <td><pre>{item.agentName}</pre></td>
        <td><pre>{item.agentType}</pre></td>
        <td><pre>{item.agentVersion}</pre></td>
        

        {/* <td><pre>{item.hostArch}</pre></td>
        <td><pre>{item.hostHostname}</pre></td>
        <td><pre>{item.hostId}</pre></td>
        <td><pre>{item.hostIp}</pre></td>
        <td><pre>{item.hostMac}</pre></td>
        <td><pre>{item.hostname}</pre></td>
        
        <td><pre>{item.osBuild.current}</pre></td>
        <td><pre>{item.osFamily.current}</pre></td>
        <td><pre>{item.osKernel.current}</pre></td>
        <td><pre>{item.osName.current}</pre></td>
        <td><pre>{item.osPlatform.current}</pre></td>
        <td><pre>{item.osType.current}</pre></td>

        <td><pre>{JSON.stringify(item.osVersion, null, 2)}</pre></td> */}
        
        <td><pre>{item.baseEventType}</pre></td>
        <td><pre>{item.baseType}</pre></td>
        
        
        <td><pre>{item.childProcessCreationTime}</pre></td>
        <td><pre>{item.childProcessElevationType}</pre></td>
        <td><pre>{item.childProcessFlsVerdict}</pre></td>
        <td><pre>{item.childProcessId}</pre></td>
        <td><pre>{item.childProcessPid}</pre></td>
        <td><pre>{item.childProcessVerdict}</pre></td>
        
        <td><pre>{item.customerId}</pre></td>
        <td><pre>{deviceName}</pre></td>
        <td><pre>{endpointId}</pre></td>
        <td><pre>{eventType}</pre></td>
        
        
        <td><pre>{item.processCreationTime}</pre></td>
        <td><pre>{item.processFlsVerdict}</pre></td>
        <td><pre>{item.processId}</pre></td>
        <td><pre>{item.processPid}</pre></td>
        <td><pre>{item.processUserName}</pre></td>
        <td><pre>{item.processVerdict}</pre></td>
        
        <td><pre>{item.sessionUser}</pre></td>
        <td><pre>{item.time}</pre></td>
        <td><pre>{item.type}</pre></td>
        <td><pre>{item.version}</pre></td>
    

        <td><pre>{item.shardsFailed}</pre></td>
        <td><pre>{item.shardsSkipped}</pre></td>
        <td><pre>{item.shardsSuccessful}</pre></td>
        <td><pre>{item.shardsTotal}</pre></td>
        
          </tr> 
        )}
        </tbody>
    </table>
  1. Your API:

Your REST API need to support paginating instead of loading all data and splitting data on frontend. It will make your application heavy and slow ( low performance if your data have million records )

You can reference: https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html

CodePudding user response:

Use array.map() inside template, just like you are using in pagination.

React doesn't like loops, it's more of a functional style library. Instead of looping almost always correct idea is some combination of array.map(), array.filter() and array.reduce().

CodePudding user response:

Use map() method for the array (ElasticSearch output) in the DOM / template. This should do the needful

  • Related