Refresh table data when tabs are selected

I am facing an issue with updating the state of a table based on status tabs selection in my application. I usually use useEffect to monitor the status tab selection and useState to update the table data. However, recently I encountered a problem where although the state is being updated (confirmed by logging the 'tableData' content right after calling setTableData), the table continues to display the previous 'tableData' state. Can anyone help me identify the root cause of this problem?

export const OrdersTab = (tabsData : any) => {
// console.log(tabsData);
const [activeTab, setActiveTab] : any = useState(null);
const [activeStatusTab, setActiveStatusTab] : any = useState();
const [tableData, setTableData]:any[] = useState([]);
const [loading, setLoading] = useState(false);

// console.log(tabsData);

useEffect(() => {
    
        if (activeStatusTab) {
            let filteredOrderes = tabsData.initTableData;
            // console.log(filteredOrderes);
            if (activeStatusTab == 'all') {
                filteredOrderes = tabsData.initTableData;
            } else {
                filteredOrderes = filteredOrderes.filter((orders:any) => 
                    orders.status.toString().toLowerCase().includes(activeStatusTab.toLowerCase())
                );
            }
            // console.log(filteredOrderes.length);
            setTableData(filteredOrderes);
            console.log(tableData.length); /* <<-- checking if state updating/not */
        }
}, [activeStatusTab]);

let statusTabs = [
    {
      id: "all",
      label: "All"
    },
    {
      id: "new",
      label: "New"
    },
    {
      id: "process",
      label: "On Process"
    },
    {
      id: "delivery",
      label: "Delivery"
    },
    {
      id: "completed",
      label: "Completed"
    },
    {
      id: "canceled",
      label: "Canceled"
    },
    {
      id: "failed",
      label: "Failed"
    },
];
return (
    <Card>
        <CardBody>
            <div className="flex w-full flex-col">
                <Tabs aria-label="Dynamic tabs" 
                    onSelectionChange={(tabKey) => setActiveTab(tabKey)}
                    fullWidth={true} 
                    items={tabsData.tabsData} >
                    {(item:any) => (
                    <Tab key={item.id} title={item.name}>
                        <Tabs aria-label="Options" onSelectionChange={(statusKey) => setActiveStatusTab(statusKey)} fullWidth={true} items={statusTabs}>
                            {(item) => (
                            <Tab key={item.id} title={item.label}>
                                    <Table id="tablexxx" aria-label="Example empty table">
                                        <TableHeader>
                                            <TableColumn>Product(s)</TableColumn>
                                            <TableColumn>Date</TableColumn>
                                            <TableColumn>Store</TableColumn>
                                            <TableColumn>Status</TableColumn>
                                            <TableColumn>Total Amount</TableColumn>
                                            <TableColumn>Courier</TableColumn>
                                            <TableColumn>Action</TableColumn>
                                        </TableHeader>
                                        {(tableData.length > 0) ? (
                                            <TableBody>
                                                {tableData.map((item:any) => (
                                                    <TableRow key={item.invoice}>
                                                        <TableCell>
                                                            <Link href={'/orders/' + item.id}>
                                                                {item.products[0].main_product.name}
                                                                <p className="text-default-400">SKU: {item.products[0].main_product.sku} x {item.products[0].qty}</p>
                                                                <p className="text-default-400">Invoice: {item.invoice}</p>
                                                            </Link>
                                                        </TableCell>
                                                        <TableCell>{item.createdAt.split('T')[0]}</TableCell>
                                                        <TableCell>{item.store.name}</TableCell>
                                                        <TableCell>{item.status}</TableCell>
                                                        <TableCell>{item.total_amount}</TableCell>
                                                        <TableCell>{item.logistic.name}</TableCell>
                                                        <TableCell>
                                                            {<Dropdown>
                                                                <DropdownTrigger>
                                                                    <Button 
                                                                    variant="bordered"
                                                                    isIconOnly  
                                                                    >
                                                                        <svg className="bi bi-three-dots-vertical" fill="currentColor" height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/></svg>
                                                                    </Button>
                                                                </DropdownTrigger>
                                                                <DropdownMenu aria-label="Static Actions">
                                                                    <DropdownItem key="new">View</DropdownItem>
                                                                    <DropdownItem key="copy"><Link href={"/orders/" + item.id}>Process</Link></DropdownItem>
                                                                    <DropdownItem key="delete" className="text-danger" color="danger">
                                                                    Reject
                                                                    </DropdownItem>
                                                                </DropdownMenu>
                                                            </Dropdown>}
                                                        </TableCell>
                                                    </TableRow>
                                                ))}
                                            </TableBody>
                                        ) : (
                                            <TableBody emptyContent={"No rows to display."}>{[]}</TableBody>
                                        )} 
                                        
                                    </Table>
                            </Tab>
                            )}
                        </Tabs>
                    </Tab>
                    )}
                    
                </Tabs>
            </div>  
        </CardBody>
    </Card>
)}

Answer â„–1

Concern: When the function setTableData(filteredOrderes) is called, React updates the state asynchronously. Therefore, if you log the length of tableData right after calling setTableData, it will still display the old value because the state update has not been applied yet.

Solution:

  1. Avoid logging the length of tableData directly after setTableData.
  2. Instead, create a separate useEffect hook that triggers when tableData changes and log its updated value there.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
import { useEffect, useState } from 'react';

export const OrdersTab = (tabsData: any) => {
  const [activeTab, setActiveTab] = useState(null);
  const [activeStatusTab, setActiveStatusTab] = useState();
  const [tableData, setTableData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  // Effect to filter table data based on selected status tab
  useEffect(() => {
    if (activeStatusTab) {
      let filteredOrders = tabsData.initTableData;
      
      if (activeStatusTab === 'all') {
        filteredOrders = tabsData.initTableData;
      } else {
        filteredOrders = filteredOrders.filter((orders: any) => 
          orders.status.toString().toLowerCase().includes(activeStatusTab.toLowerCase())
        );
      }

      // Update tableData state with filtered orders
      setTableData(filteredOrders);
    }
  }, [activeStatusTab, tabsData.initTableData]);

  // Effect to log the updated tableData when it changes
  useEffect(() => {
    console.log('Updated tableData length:', tableData.length);
  }, [tableData]); // This effect runs whenever tableData is updated

  let statusTabs = [
    { id: "all", label: "All" },
    { id: "new", label: "New" },
    { id: "process", label: "On Process" },
    { id: "delivery", label: "Delivery" },
    { id: "completed", label: "Completed" },
    { id: "canceled", label: "Canceled" },
    { id: "failed", label: "Failed" },
  ];

  return (
    <Card>
      <CardBody>
        <div className="flex w-full flex-col">
          <Tabs
            aria-label="Dynamic tabs"
            onSelectionChange={(tabKey) => setActiveTab(tabKey)}
            fullWidth={true}
            items={tabsData.tabsData}
          >
            {(item: any) => (
              <Tab key={item.id} title={item.name}>
                <Tabs
                  aria-label="Options"
                  onSelectionChange={(statusKey) => setActiveStatusTab(statusKey)}
                  fullWidth={true}
                  items={statusTabs}
                >
                  {(item) => (
                    <Tab key={item.id} title={item.label}>
                      <Table id="tablexxx" aria-label="Example empty table">
                        <TableHeader>
                          <TableColumn>Product(s)</TableColumn>
                          <TableColumn>Date</TableColumn>
                          <TableColumn>Store</TableColumn>
                          <TableColumn>Status</TableColumn>
                          <TableColumn>Total Amount</TableColumn>
                          <TableColumn>Courier</TableColumn>
                          <TableColumn>Action</TableColumn>
                        </TableHeader>
                        {tableData.length > 0 ? (
                          <TableBody>
                            {tableData.map((item: any) => (
                              <TableRow key={item.invoice}>
                                <TableCell>
                                  <Link href={'/orders/' + item.id}>
                                    {item.products[0].main_product.name}
                                    <p className="text-default-400">
                                      SKU: {item.products[0].main_product.sku} x {item.products[0].qty}
                                    </p>
                                    <p className="text-default-400">Invoice: {item.invoice}</p>
                                  </Link>
                                </TableCell>
                                <TableCell>{item.createdAt.split('T')[0]}</TableCell>
                                <TableCell>{item.store.name}</TableCell>
                                <TableCell>{item.status}</TableCell>
                                <TableCell>{item.total_amount}</TableCell>
                                <TableCell>{item.logistic.name}</TableCell>
                                <TableCell>
                                  <Dropdown>
                                    <DropdownTrigger>
                                      <Button variant="bordered" isIconOnly>
                                        <svg
                                          className="bi bi-three-dots-vertical"
                                          fill="currentColor"
                                          height="16"
                                          viewBox="0 0 16 16"
                                          width="16"
                                          xmlns="http://www.w3.org/2000/svg"
                                        >
                                          <path d="M9.5 13a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm0-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z" />
                                        </svg>
                                      </Button>
                                    </DropdownTrigger>
                                    <DropdownMenu aria-label="Static Actions">
                                      <DropdownItem key="new">View</DropdownItem>
                                      <DropdownItem key="copy">
                                        <Link href={"/orders/" + item.id}>Process</Link>
                                      </DropdownItem>
                                      <DropdownItem key="delete" className="text-danger" color="danger">
                                        Reject
                                      </DropdownItem>
                                    </DropdownMenu>
                                  </Dropdown>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        ) : (
                          <TableBody emptyContent={"No rows to display."}>{[]}</TableBody>
                        )}
                      </Table>
                    </Tab>
                  )}
                </Tabs>
              </Tab>
            )}
          </Tabs>
        </div>
      </CardBody>
    </Card>
  );
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript to parse an XML document on a WAMP server

I am a beginner in the field of web development and currently struggling with parsing an XML document using JavaScript on WAMP server. I know that both the web page and XML file need to be on the same server for it to work. I tried placing both the PHP and ...

I am experiencing an issue where tapping on the Status Bar in MobileSafari is not functioning correctly on a specific

I am struggling to troubleshoot this problem with no success so far. The HTML5 JavaScript library I'm developing has a test page that can display a large amount of output by piping console.log and exceptions into the DOM for easy inspection on mobile ...

I ran into yet another roadblock while attempting to set up my react application

While trying to install template dependencies using npm, an error occurred. The error message stated: "npm ERR! Unexpected end of JSON input while parsing near '... PGP SIGNATURE-----\r' npm ERR! A complete log of this run can be found in: n ...

What is the best way to extract and connect data from a JSON file to a dropdown menu in Angular 2+?

Here is an example of my JSON data: { "Stations": { "44": { "NAME": "Station 1", "BRANCH_CD": "3", "BRANCH": "Bay Branch" }, "137": { "NAME": "Station 2", ...

What is the most effective method for clearing the `useState` value stored in localstorage after adding new data to localstorage?

I am working on a React/typescript app where I need to fetch data from local storage and add new data on a mouse click event. To achieve this, I have created a custom hook: const useLocalStorage = (name: string, defaultValue: []) => { const [currentVa ...

What are the best scenarios for implementing PHP(cURL) instead of JavaScript (Axios, Ajax, Fetch)?

When deciding between using a JavaScript program or a PHP one to interact with a web API for making HTTP requests such as POST and GET, which option would be more suitable? ...

Saving URLSearchParams to a file using javascript

I am currently implementing jstree and I need to be able to click on a file within the tree structure in order to display a PDF file. Below is the relevant code snippet: $(function () { $('#tree').jstree({ 'core' : { ...

A concise way to write an else if statement in Javascript and jQuery

Is there a way to make this code more concise? It works perfectly fine, but it's too lengthy. Basically, the code involves two dropdown lists where the user selects options, and based on their selection, values appear in two textboxes. The catch is th ...

Need help with Jquery JSON Request - I can successfully retrieve the Array but struggling to showcase it

Seeking assistance with using an API that retrieves information about ARK servers, such as the number of online players. The API can be found at this link: ... I have managed to obtain the array using a basic script I stumbled upon, but I am not well-ver ...

Executing Client-Side Function Upon Data Retrieval in a Node.js Application

Within my node.js Express application, there exists a route like this: router.get('/devices/:id/visualize', catchErrors(deviceController.visualizeDevice)); This route points to the following controller: exports.visualizeDevice = async (req, re ...

The offset values of $(element) keep increasing indefinitely when they are updated repeatedly

After researching how to utilize JavaScript drag functionality to move elements, the goal is to dynamically adjust the cursor position within a square when dragged. In an attempt to simplify the process and avoid storing x and y offsets as separate variabl ...

I encountered a problem when making multiple JSON calls within a for loop

for(var j = 0; j < tempArray.length; j ++){ $.getJSON('http://localhost:8080/predict', tempArray[j]) .fail(function(data,textStatus, error) { Probability = data.responseText; console.error("getJSON failed, status: " + textStat ...

Dealing with the percentage sign in table names during data retrieval

When using React and Express to retrieve and store data in JSON format, what is the correct way to reference tables that have a percentage sign in their name? componentDidMount() { // Retrieve data from http://localhost:5000/citystats, sort by ID, t ...

Struggling to load app.css, main.js, and other files while using an Express server

I'm struggling with my code setup. Essentially, I have the following piece of code: var express = require('express'); var app = express(); var server = require('http').Server(app); app.get('/', function(req,res){ res.s ...

Intellisense in VS Code is failing to work properly in a TypeScript project built with Next.js and using Jest and Cypress. However, despite this issue,

I'm in the process of setting up a brand new repository to kick off a fresh project using Next.js with TypeScript. I've integrated Jest and Cypress successfully, as all my tests are passing without any issues. However, my VSCode is still flagging ...

Angular routing and parameters are not functioning as expected

In my code, I have implemented the following controller: app.controller('ObjectBoardCtrl', ['$scope' , '$rootScope' , '$routeParams' , function($scope , $rootScope, $routeParams) { $scope.selectedObjectId = $ ...

What is the purpose of using detectChanges() when utilizing the default change detection strategy in Angular?

Currently, I am facing an issue while working on my Angular 4 application. I have noticed that I need to use this.changeDetectorRef.detectChanges(); to update the view whenever there is a change in the model. This requirement arises in scenarios like pagin ...

Error: The version of @ionic-native/[email protected] is not compatible with its sibling packages' peerDependencies

When attempting ionic cordova build android --prod, the following error occurred: I have tried this multiple times. rm -rf node_modules/ rm -rf platforms/ rm -rf plugins/ I deleted package.lock.json and ran npm i, but no luck so far. Any ideas? Er ...

The $.ajax() method is unable to fulfill a request for retrieving JSON data from a static JSON file

Having difficulty fetching JSON data from a static .json file located on an xampp server. I've successfully used getJSON for this task, but encountering issues with $.ajax(). Any assistance in identifying the error would be greatly appreciated. $.aj ...

What is causing Vuejs to not recognize the status of my button?

I am currently developing a Vuejs website that allows users to jot down notes about meetings. Upon loading, the website fetches the meeting notes from the server and displays them. When a user adds new notes and clicks the "Save" button, the text is saved ...