Neff
Neff

Reputation: 189

Get and Map react Js

my problem here , I get a database and of course I map it unfortunately in my result it shows me all the data while I would only like to display the last recorded data do you have any idea? I let you watch the following code thank you for your help Neff

import React, { Component } from 'react';
import { CardText,  Col, } from 'reactstrap';
import axios from 'axios'

const entrypoint = process.env.REACT_APP_API_ENTRYPOINT+'/api';

class randomNumber  extends Component {

constructor(props) {
    super(props);
    this.state = {
        data: [],

    };
}
getRandom = async () => {        
    const res = await axios.get(
        entrypoint + "/alluserpls"
    )
    this.setState({ data: res.data })
}
componentDidMount() {
    this.getRandom()
}
render() {            
    let datas = this.state.data.map(datass => {
        return (
            <div>
              < Col sm="12" key={datass.id}>
           <div key="a"> 
      <CardText className="textForAdminPageButHereIsForRandomId">{datass.randomID}</CardText>
    </div>
  </Col>
            </div>
          )
        })
        return (    
                    <div className="box">  
                {datas}     
                </div>
        )
    }
}

export default randomNumber

Upvotes: 0

Views: 50

Answers (1)

Joe Lloyd
Joe Lloyd

Reputation: 22353

Use index to pick the data you want

In this case you will need to find the last index. this is data.length - 1

Then you can get the very last data by simply going data[data.length - 1]

let datas = (this.state.data && this.state.data.length) && this.state.data[this.state.data.length - 1];

return datas ? (    
<div className="box">  
  <div>
   < Col sm="12" key={datas.id}>
    <div key="a"> 
      <CardText className="textForAdminPageButHereIsForRandomId">{datas.randomID}      
      </CardText>
    </div>
  </Col>
 </div>     
</div>) : null;

Upvotes: 1

Related Questions