0

I'm coding and I got stuck with some issue with JSX.

How can I count index in the .map() method?

I need to get only the first 5 title in my code, I use the axios module to get the data from an database, and I need to get only the first 5 titles in my state.

import React, {Component} from "react"
import UserUtils from "./UserUtils"
class Ex6_2Comp extends Component
{
    constructor()
    {
        super()
        this.state = {userid : "" , user : {} ,titles : []}
    }
    getData =  async () =>
    {
        let resp = await UserUtils.getUserFullData(`http://jsonplaceholder.typicode.com/users/${this.state.userid}`);
        await this.setState({user : resp.data})
        let resp_todo = await UserUtils.getUserFullTodos()
        let AllTitle = resp_todo.filter(x => x.userId == this.state.userid)
        let userTitle = AllTitle.map(x =>x.title)
        this.setState({titles : userTitle})
        

        
    }
    render()
    {
        
        let items = this.state.titles.map((item,index) => 
                {
                    
                    return <li key={index}>{item}</li>
                })
       
       
        return(
            <div className="App">
             Id:   <input type="text" onChange={e => this.setState({userid : e.target.value})}></input>
            <br/>
            <input type="button" value="getData" onClick={this.getData}/>
            <br/>
            Name : {this.state.user.name}
            <br/>
            email : {this.state.user.email}
            <br/>
            <ul>
                {items}
            </ul>
            </div>
        )
    }
}
export default Ex6_2Comp

1 Answer 1

1

You can use .slice() as the following:

let items = this.state.titles.slice(0, 5)
                             .map((item,index) => <li key={index}>{item}</li>)

Read from the documentation of .slice():

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

See a working example with .slice(0, 5) as:

const titles = [{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},{id:7}]
const result = titles.slice(0, 5)

console.log({result})

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.