Home > Net >  Update the table if value is unique
Update the table if value is unique

Time:02-10

I have a query in reactjs.

The thing is, I want to render a table on my screen, as per the updated data. I am using get api to call the data, but what i need to do is to render the latest data corresponding to unique id. Otherwise show all data.

CodePudding user response:

Let you received the props which has duplicate records like

data = [{
  id: 1,
  x: 40,
  y: 30,
  x: 20,
  e: 230
},{
  id: 2,
  x: 42,
  y: 32,
  x: 22,
  e: 232
},{
  id: 3,
  x: 41,
  y: 31,
  x: 21,
  e: 231
},
{
  id: 1,
  x: 4,
  y: 3,
  x: 2,
  e: 23
}];

Requirement: As per this data you want to render for unique ids with latest value id=1,2 and 3.

import React from "react";
import "./style.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: this.getUniqueAndUpdatedRecords(props) }
    console.log(this.state.data);
  }

  getUniqueAndUpdatedRecords(data) {
    return data.data.filter(function ({ id }) {
      return !this.has(id) && this.add(id);
    }, new Set());
  }

  render() {
    return <table>
      <thead>
        <tr>
          <th>x</th>
          <th>y</th>
          <th>z</th>
          <th>e</th>
        </tr>
      </thead>
      <tbody>
        {(this.state.data && this.state.data.length ? (this.state.data.map(({ id, x, y, z, e }) => {
          return <tr key={id}>
            <td>{x}</td>
            <td>{y}</td>
            <td>{z}</td>
            <td>{e}</td>
          </tr>
        })) : "")}
      </tbody>
    </table>
  }
}

Note: As per this code your id=1 which is first index of data will be rendered. if you want id=1 with fourth index will be latest then reverse your data array

data = data.reverse();

Added this example as ref: https://stackblitz.com/edit/react-jditah?file=src/index.js

CodePudding user response:

<tbody>
 {this.props.data && this.props.data.length ?
    (this.props.data.map((item,i,arr) => {
        return (
      // item.a === this.props.data.a ?
         <TableValue
           x={item['x']}
           y={item['y']}
           z={item['z']}
           e={item['e']}
          />
      // :""

So this where data is adding to table....Now I need that if let say we have 4 fields---> 2 with same id and 2 with different id. So I need to render 3 fields only . For same id, the updated one should render

  • Related