React JS - Transform a static pagination to dynamic from JSON - javascript

I have a ReactJS code below made for a SO user Piotr Berebecki. The code is working succefully It is a handle pagination returning items from an array. I want to do the same thing but returning data from JSON DB How can I do? How can I solve it? Thank you. Here is the app in the CodePen.
Here is My DB Json. I want only return the images (named as 'fotos'). It will replace the 'todos' in the array in the second code below
. Note: It must be made by Axios.
{
"interiores": [
{
"nome": "house 1",
"descricao": "This is the description of the house 1",
"fotos": [
"int_02", "int_02", "int_02", "int_02", "int_02"
]
}
]
}
Code:
import React, { Component } from 'react'
class Todo extends Component {
constructor() {
super();
this.state = {
todos: ['a','b','c','d','e','f','g','h','i','j','k'],
currentPage: 1,
todosPerPage: 3
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderTodos}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
export default Todo;

It seems like you're asking how to handle the data once you've already made the call, this is how I think you should do it using componentDidMount I haven't tested it yet, but should give you a good starting point.
{
"interiores": [
{
"nome": "house 1",
"descricao": "This is the description of the house 1",
"fotos": [
"int_02", "int_02", "int_02", "int_02", "int_02"
]
}
]
}
import React, { Component } from 'react'
class Todo extends Component {
constructor() {
super();
this.state = {
todos: ['a','b','c','d','e','f','g','h','i','j','k'],
currentPage: 1,
todosPerPage: 3 ,
fotos: '',
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
async componentDidMount() {
//make call to database and set the db data to your state.
const dbData = axios.get('http://yourapi.com/todods')
.then(function (response) {
this.setState({fotos: response.data.interiores[0].fotos})
})
.catch(function (error) {
console.log('error:', error);
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{this.state.fotos? this.state.fotos : 'nothing to display' }
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
export default Todo;

Related

React.js + Socket.io updating state changes position of list items

export default class extends React.Component {
constructor(props) {
super(props)
this.state = {
status: [],
services: []
}
getAppData((err,opt, data) => {
function Exists(list, id) {
return list.some(function(el) {
return el.data.id == id;
});
}
if (opt == "sysinfo"){
var filtered = this.state.status;
if (Exists(filtered, data.id)){
filtered = this.state.status.filter(function(el) { return el.data.id != data.id; });
}
filtered.push({ data })
this.setState({status: filtered})
} else if (opt == "init_services"){
this.setState({services: data})
}
});
}
render() {
const timestampforuse = this.state.status
const totalList = this.state.services
console.log(totalList)
const mainList = totalList.map((link) =>
<ListGroup.Item key={link.id} keyProp={link.id}>Name: {link.name} Node: {link.node}</ListGroup.Item>
);
console.log(totalList)
const listItems = timestampforuse.map((link) =>
<ListGroup.Item ><p key={link.data.id}>ID: {link.data.pid} Node: {link.data.node} <br/>Ram usage: {link.data.p_ram.toFixed(2)} / 100% Cpu usage: {link.data.p_cpu.toFixed(2)} / 100%</p></ListGroup.Item>
);
return (
<div>
<ListGroup>
{mainList}
</ListGroup>
</div>
);
}
}
Data from sysinfo:
{
cores: 16,
cpu: 0,
id: "00ffab6ca93243f08eb10670d9c491d54cf674173d13c24a0a663ebb3f5e54d042ae",
node: "1",
p_cpu: 0,
p_ram: 0.18230482881430612,
pid: 29216,
ram: 28.78515625,
threads: 5,
time: 1609179904302,
time_from_startup: 1609179876.271594,
time_since_boot: 1608562209.0201786
}
Data for init:
add_game: true
description: "a test script"
id: "00ffab6ca93243f08eb10670d9c491d54a0a663ebb3f5e54d042ae"
name: "test331112321"
node: "1"
Socket script:
import openSocket from 'socket.io-client';
const socket = openSocket('http://localhost:3000');
function getAppData(cb) {
socket.on('update_system', data => cb(null,"sysinfo", data));
socket.on('init_services', data => cb(null,"init_services", data));
socket.emit('updated', 1000);
}
export { getAppData };
I have tried using a map and using it as a list but when it updates every second it updates too fast to even read. How would I make the name appear, then once data gets sent have that update the list but not update the entire list? At the moment, it allows it to update and change, and no issues if it's 1 item being updated but if there are 2 or more it updates too fast to see. How do I get around this?
I have fixed this by updating an array of objects on the server-side. Updating a service on that list and returning the entire list. This tackled the issue of having it update too fast.
End code front end code:
export default class extends React.Component {
constructor(props) {
super(props)
this.state = {
services: []
}
getAppData((err,opt, data) => {
if (opt == "sysinfo"){
this.setState({services: data})
}
});
}
componentDidMount() {
fetch("http://localhost:3000/api/v1/bot/me/getservices").then(res => res.json()).then(data =>{
console.log(data)
this.setState({services: data})
})
}
render() {
const totalList = this.state.services
const listItems = totalList.map((link) =>
<ListGroup.Item key={link.id}>Name: {link.name} Node: {link.node} <br/>Ram usage: {link.p_ram.toFixed(2)} / 100% Cpu usage: {link.p_cpu.toFixed(2)} / 100%</ListGroup.Item>
);
return (
<div>
<ListGroup>
{listItems}
</ListGroup>
</div>
);
}
}

ReactJS - covering with '0' the blank spaces

I have this ReactJS App
See the app working
https://codepen.io/claudio-bitar/pen/VERORW
It returns a pagination with at maximum eight numbers per page.
Example:
I have ten numbers, so
Page one: 1, 2, 3, 4, 5, 6, 7, 8
page two: 9, 10
I would like to cover with '0' the blank numbers space until I reached 8 numbers. For example in the page two I would like to return:
9, 10, 0, 0, 0, 0, 0, 0
How can I solve it? Thank you
The App code:
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos: {
"elements": ['1','2','3','4','5','6','7','8','9','10']
},
currentPage: 1,
todosPerPage: 8
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.elements.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.elements.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderTodos}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('app')
);
You could create a loop that will loop until currentTodos has todosPerPage elements in it and just push 0 until it does.
class TodoApp extends React.Component {
// ...
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.elements.slice(
indexOfFirstTodo,
indexOfLastTodo
);
while (currentTodos.length !== todosPerPage) {
currentTodos.push(0);
}
// ...
}
}
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos: {
elements: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
},
currentPage: 1,
todosPerPage: 8
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.elements.slice(
indexOfFirstTodo,
indexOfLastTodo
);
while (currentTodos.length !== todosPerPage) {
currentTodos.push(0);
}
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.elements.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li key={number} id={number} onClick={this.handleClick}>
{number}
</li>
);
});
return (
<div>
<ul>{renderTodos}</ul>
<ul id="page-numbers">{renderPageNumbers}</ul>
</div>
);
}
}
ReactDOM.render(<TodoApp />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

React-Bootstrap - Pagination not showing

I'm using the react-bootstrap to paginate the result. It is rendering the div #content, but it is not showing nothing more. It is showing only a empty div with width, height and background color as I configured on the CSS file. I would like to display the pagination showing one house per page. The result of data from JSON is catched successfully. How can I solve the pagination issue? Thanks!
import React, { Component } from 'react'
import axios from 'axios'
import { Pagination } from 'react-bootstrap'
const URL_HOUSES = 'http://localhost:3001/houses';
class Casas extends Component {
constructor(props) {
super(props)
this.state = {
houses: []
}
this.handlePageChange = this.handlePageChange.bind(this)
}
getNumPages(currentPage) {
{ this.handlePageChange }
this.setState({
per_page: this.props.results ,
currentPage: currentPage + 1 ,
previousPage: currentPage - 1
});
}
handlePageChange(page, evt) {
const currentPage = this.state.currentPage || 1;
const numPages = this.getNumPages();
const pageLinks = [];
if (currentPage > 1) {
if (currentPage > 2) {
pageLinks.push(1);
pageLinks.push(' ');
}
pageLinks.push(currentPage - 1);
pageLinks.push(' ');
}
for (let i = 1; i <= numPages; i++) {
const page = i;
pageLinks.push(page);
}
if (currentPage < numPages) {
pageLinks.push(' ');
pageLinks.push(currentPage + 1);
if (currentPage < numPages - 1) {
pageLinks.push(' ');
pageLinks.push(numPages);
}
}
this.setState({ currentPage: currentPage + 1 } );
this.setState({ previousPage: currentPage - 1 } );
}
componentDidMount() {
axios.get(URL_HOUSES)
.then(res => {
this.setState({ houses: res.data })
})
}
render() {
const per_page = "1";
const paginationData = this.state.houses
let numPages = Math.ceil(paginationData.length / per_page);
if (paginationData.length % per_page > 0) {
numPages++;
}
return (
<div>
{this.state.houses.map(item =>
<div>
<h2>{item.name}</h2>
<p>{item.description}</p>
<ul>
{
item.photos.map(photo => <li>{photo}</li>)
}
</ul>
</div>
)}
<Pagination id="content" className="users-pagination pull-right"
bsSize="medium"
first last next prev boundaryLinks items={numPages}
activePage={ this.state.currentPage } onSelect={ this.handlePageChange
} />
</div>
)
}
}
export default Houses;
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Pagination from "react-js-pagination";
require("bootstrap/less/bootstrap.less");
class App extends Component {
constructor(props) {
super(props);
this.state = {
activePage: 1,
itemPerPage: 3,
productList: [],
duplicateProductList: []
};
}
componentDidMount() {
let d = '';
$.get("YOUR API", function (data) {
d = data;
this.setState({
projectList: d,
duplicateProductList: d
});
}.bind(this));
}
handlePageChange(pageNumber) {
this.setState({ activePage: pageNumber });
}
render() {
const { projectList, activePage, itemPerPage } = this.state;
const indexOfLastTodo = activePage * itemPerPage;
const indexOfFirstTodo = indexOfLastTodo - itemPerPage;
const renderedProjects = projectList.slice(indexOfFirstTodo, indexOfLastTodo);
return (
<div>
<div>
YOUR LIST
</div>
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={this.state.itemPerPage}
totalItemsCount={this.state.duplicateProductList.length}
pageRangeDisplayed={5}
onChange={this.handlePageChange.bind(this)}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Can you follow this link https://www.npmjs.com/package/react-js-pagination

How do I setState of object.item[n] nested within array which is nested within an array of objects

I have following data structure:
const library = [
{
procedureName:'Build Foundations',
id:1,
tasks:[
{
taskName:'dig at least 1m deep', isCompleted:false, procedureId:1
},
{
taskName:'At least 50m wide digging', isCompleted:false, procedureId:1
},
{
taskName:'Buy megazords', isCompleted:false, procedureId:1
}
]
},
{
procedureName:'Building the roof',
id:2,
tasks:[
{
taskName:'Constructed according to the project', isCompleted:false, procedureId:2
},
{
taskName:'Protect wood from humidity', isCompleted:false, procedureId:2
},
{
taskName:'Roof build with the correct angle', isCompleted:false, procedureId:2
}
]
}
]
I want my function onTaskToggle to setState of library.tasks.isCompleted like this: library.tasks.isCompleted: !library.tasks.isCompleted
(I want to be able to distinguish the click of certain item as well)
I have no idea how get to this state.
Should I build my data structure differently or is there something I am missing?
onTaskToggle = (task) => {
const findProcedure = library => library.filter(procedure => procedure.id === task.procedureId);
const findTask = tasks => tasks.filter(singleTask => singleTask.taskName === task.taskName);
const toggledTask = findTask(findProcedure(this.state.library)[0].tasks);
const procedureIndex = this.state.library.indexOf(findProcedure(this.state.library)[0]);
const toggledTaskIndex = this.state.library[procedureIndex].tasks.indexOf(toggledTask[0]);
const insideProcedure = this.state.library[procedureIndex];
const insideTask = this.state.library[procedureIndex].tasks.indexOf(toggledTask[0]);
this.setState({
// Stuck there ...library
})
}
I'm not sure if it is needed, but that's the way I'm passing the data:
// Main component
class App extends Component {
constructor(props){
super(props);
this.state = {
projects,
library,
}
}
onTaskToggle = (task) => {
const findProcedure = library => library.filter(procedure => procedure.id === task.procedureId);
const findTask = tasks => tasks.filter(singleTask => singleTask.taskName === task.taskName);
const toggledTask = findTask(findProcedure(this.state.library)[0].tasks);
const procedureIndex = this.state.library.indexOf(findProcedure(this.state.library)[0]);
const toggledTaskIndex = this.state.library[procedureIndex].tasks.indexOf(toggledTask[0]);
const insideProcedure = this.state.library[procedureIndex];
const insideTask = this.state.library[procedureIndex].tasks.indexOf(toggledTask[0]);
this.setState({
// ...library
})
}
render() {
const {projects, library} = this.state;
return (
<div>
<Procedures library={library} onTaskToggle={this.onTaskToggle}/>
</div>
);
}
}
export default class Procedures extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
{
<ProceduresList library={this.props.library} onTaskToggle={this.props.onTaskToggle}/>
}
</div>
);
}
}
//Mapping through procedures
const ProceduresList = props => {
const list = props.library.map(procedure => {
const { id, procedureName, tasks } = procedure;
return(
<div key={id}>
<h4>{procedureName} </h4>
<div><ListingTasks tasks={tasks} onTaskToggle={props.onTaskToggle}/></div>
</div>
)
})
return <div>{list}</div>
}
export default ProceduresList;
// Last Component where all the magic shall happen
const ListingTasks = (props) => {
const list = props.tasks.map(task => { // under this line goes mapping through procedures
const taskName = task.taskName;
return <div key={taskName} onClick={() => props.onTaskToggle(task)}>{taskName}</div>
})
return <div>{list}</div>
}
export default ListingTasks
onTaskToggle(task) {
const { library } = this.state
const procedure = Object.assign({}, library.find(proc => (proc.id === task.procedureId)))
const procedureIndex = library.findIndex(prec => prec.id === procedure.id)
procedure.tasks = procedure.tasks.map((tsk) => {
if (tsk.taskName === task.taskName) {
tsk.isCompleted = !tsk.isCompleted
}
return tsk;
})
library.splice(procedureIndex, 1, procedure)
this.setState({ library })
}

Infinite scroll for React List

So I have a list of 5k elements. I want to display them in parts, say each part is 30 items. The list of items is in the component's state. Each item is an object taken from the API. It has properties on which I have to make an API call. By parts, to avoid enormous load time. So this is what I've got so far(simplified):
let page=1;
class GitHubLists extends Component {
constructor(props) {
super(props);
this.state = {
repos: [],
contributors: []
}
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
axios.get(org)
.then(res => setState({contributors: res})
}
handleScroll() {
page++;
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
render() {
const contributors = this.state.contributors.slice(0,30*page).map(contributor =>
<li key={contributor.id}>{contributor.login} {contributor.contributions}<a href={contributor.url}>View on GitHub</a></li>
);
return (
<div onScroll={this.handleScroll}>{contributors}</div>
)
}
}
Like I said each item(contributor in this case) has properties which values are links for the API calls. 3 to be exact. On each one of them, I need to make an API call, count the items inside the response and display them.
You can use react-virtualized (6.8k stars), it has been designed for this purpose.
Here is an official example with a list of 1000 elements or here with a Infinite Loader.
I wrote an easier live example here where you can modify code.
For your problem, you need to do your API calls in the rowRenderer and play with the overscanRowCount to prefetch rows. (docs of the List component)
I've made a simple pagination adapted from another GIST that I've already used that makes total sense for your purpose, you just need to implement your code.
class ItemsApp extends React.Component {
constructor() {
super();
this.state = {
items: ['a','b','c','d','e','f','g','h','i','j','k','2','4','1','343','34','a','b','c','d','e','f','g','h','i','j','k','2','4','1','343','34','a','b','c','d','e','f','g','h','i','j','k','2','4','1','343','34','33'],
currentPage: 1,
itemsPerPage: 30
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { items, currentPage, itemsPerPage } = this.state;
// Logic for displaying current items
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);
const renderItems = currentItems.map((item, index) => {
return <li key={index}>{item}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(items.length / itemsPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderItems}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
ReactDOM.render(
<ItemsApp />,
document.getElementById('app')
);
https://codepen.io/anon/pen/jLZjQZ?editors=0110
Basically, you should insert your fetched array inside the items state, and change the itemsPerPage value according to your needs, I've set 30 occurrences per page.
I hope it helps =)
Ok, there is definitely something wrong about how I wrote my app. It is not waiting for all API calls to finish. It sets the state (and pushes to contributors) multiple times. This is the full code:
let unorderedContributors = [];
let contributors = [];
class GitHubLists extends Component {
constructor(props) {
super(props);
this.state = {
repos: [],
contributors: [],
currentPage: 1,
itemsPerPage: 30,
isLoaded: false
};
this.handleClick = this.handleClick.bind(this)
}
componentWillMount() {
//get github organization
axios.get(GitHubOrganization)
.then(res => {
let numberRepos = res.data.public_repos;
let pages = Math.ceil(numberRepos/100);
for(let page = 1; page <= pages; page++) {
//get all repos of the organization
axios.get(`https://api.github.com/orgs/angular/repos?page=${page}&per_page=100&${API_KEY}`)
.then(res => {
for(let i = 0; i < res.data.length; i++) {
this.setState((prevState) => ({
repos: prevState.repos.concat([res.data[i]])
}));
}
})
.then(() => {
//get all contributors for each repo
this.state.repos.map(repo =>
axios.get(`${repo.contributors_url}?per_page=100&${API_KEY}`)
.then(res => {
if(!res.headers.link) {
unorderedContributors.push(res.data);
}
//if there are more pages, paginate through them
else {
for(let page = 1; page <= 5; page++) { //5 pages because of GitHub restrictions - can be done recursively checking if res.headers.link.includes('rel="next"')
axios.get(`${repo.contributors_url}?page=${page}&per_page=100&${API_KEY}`)
.then(res => unorderedContributors.push(res.data));
}
}
})
//make new sorted array with useful data
.then(() => {contributors =
_.chain(unorderedContributors)
.flattenDeep()
.groupBy('id')
.map((group, id) => ({
id: parseInt(id, 10),
login: _.first(group).login,
contributions: _.sumBy(group, 'contributions'),
followers_url: _.first(group).followers_url,
repos_url: _.first(group).repos_url,
gists_url: _.first(group).gists_url,
avatar: _.first(group).avatar_url,
url: _.first(group).html_url
}))
.orderBy(['contributions'],['desc'])
.filter((item) => !isNaN(item.id))
.value()})
.then(() =>
this.setState({contributors, isLoaded: true})
)
)
})
}
})
}
handleClick(event) {
this.setState({currentPage: Number(event.target.id)})
}
render() {
const { contributors, currentPage, contributorsPerPage } = this.state;
//Logic for displaying current contributors
const indexOfLastContributor = currentPage * contributorsPerPage;
const indexOfFirstContributor = indexOfLastContributor - contributorsPerPage;
const currentContributors = contributors.slice(indexOfFirstContributor, indexOfLastContributor);
const renderContributors = currentContributors.map((contributor, index) => {
return <li key={index}>{contributor}</li>;
});
//Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(contributors.length / contributorsPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderContributors}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
How can I fix it so the state is set once and then I can render contributors from the state (and making API calls with values of the properties: followers_url, repos_url and gists_url)?

Categories

Resources