I have the code below which reads stores and updates data to and from from localstorage and it works fine with AngularJS.
Here is my issue:
Am trying to re-write the Angularjs code to React but it throws error unexpected token.
AngularJS:
<script>
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
//called at initiazation, reads from localstorage if array is present there
$scope.checkAndInitiateFromLocalStorage = function() {
var readArrayStr = localStorage.getItem('messagingArray');
if (readArrayStr && readArrayStr.length > 0) {
$scope.arr = JSON.parse(readArrayStr);
} else {
$scope.arr = [{
name: "user1"
},
{
name: "user2"
},
{
name: "user3"
},
{
name: "user4"
}
];
}
}
//called at each update, stores the latest status in localstorage
$scope.updateLocalStorage = function() {
localStorage.setItem('messagingArray', JSON.stringify($scope.arr));
/* console.log("updated local storage !!"); */
}
$scope.checkAndInitiateFromLocalStorage();
});
</script>
React:
<script src="react.min.js"></script>
<script src="react-dom.min.js"></script>
<script src="browser.min.js"></script>
<div id="app"></div>
<script type="text/babel">
class Application extends React.Component {
constructor(props) {
super(props);
//called at initiazation, reads from localstorage if array is present there
//const checkAndInitiateFromLocalStorage () {
const checkAndInitiateFromLocalStorage = () => {
var readArrayStr = localStorage.getItem('messagingArray');
if (readArrayStr && readArrayStr.length > 0) {
this.state.arr = JSON.parse(readArrayStr);
} else {
this.state = {
arr: [
{ name: "user1"},
{ name: "user2"},
{ name: "user3"},
{ name: "user4"}
],
};
}
}
this.checkAndInitiateFromLocalStorage = this.checkAndInitiateFromLocalStorage.bind(this);
this.updateLocalStorage = this.updateLocalStorage.bind(this);
}
//called at each update, stores the latest status in localstorage
updateLocalStorage() {
localStorage.setItem('messagingArray', JSON.stringify(this.state.arr));
};
componentDidMount() {
this.checkAndInitiateFromLocalStorage();
this.updateLocalStorage();
}
render() {
return (
<div>
<h3>Display Data</h3>
<ul>
{this.state.arr.map((obj, i) => (
<li key={i}>
{obj.name} - {obj.name}
</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(<Application />, document.getElementById('app'));
</script>
Here is the updated react error message:
Uncaught TypeError: Cannot read properties of undefined (reading 'bind')
at new Application (eval at transform.run
This issue was solved by Moving the definition of checkAndInitiateFromLocalStorage outside of the constructor.
Here is the code below
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [
{ name: "user1"},
{ name: "user2"},
{ name: "user3"},
{ name: "user4"}
],
};
this.checkAndInitiateFromLocalStorage = this.checkAndInitiateFromLocalStorage.bind(this);
this.updateLocalStorage = this.updateLocalStorage.bind(this);
}
checkAndInitiateFromLocalStorage () {
//const checkAndInitiateFromLocalStorage = () => {
var readArrayStr = localStorage.getItem('messagingArray');
if (readArrayStr && readArrayStr.length > 0) {
this.state.arr = JSON.parse(readArrayStr);
} else {
this.state.arr;
}
}
//called at each update, stores the latest status in localstorage
updateLocalStorage() {
localStorage.setItem('messagingArray', JSON.stringify(this.state.arr));
};
componentDidMount() {
this.checkAndInitiateFromLocalStorage();
this.updateLocalStorage();
}
render() {
return (
<div>
<h3>Display Data</h3>
<ul>
{this.state.arr.map((obj, i) => (
<li key={i}>
{obj.name} - {obj.name}
</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(<Application />, document.getElementById('app'));
Related
I am tickling with Algolia autocomplete, and I am trying to replicate their custom renderer in react using the class component. This is the sandbox of the minimal demo of custom renderer using functional component,
and here is my attempt to convert it into a class component.
import { createAutocomplete } from "#algolia/autocomplete-core";
import { getAlgoliaResults } from "#algolia/autocomplete-preset-algolia";
import algoliasearch from "algoliasearch/lite";
import React from "react";
const searchClient = algoliasearch(
"latency",
"6be0576ff61c053d5f9a3225e2a90f76"
);
// let autocomplete;
class AutocompleteClass extends React.PureComponent {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.autocomplete = null;
this.state = {
autocompleteState: {},
};
}
componentDidMount() {
if (!this.inputRef.current) {
return undefined;
}
this.autocomplete = createAutocomplete({
onStateChange({ state }) {
// (2) Synchronize the Autocomplete state with the React state.
this.setState({ autocompleteState: state });
},
getSources() {
return [
{
sourceId: "products",
getItems({ query }) {
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: "instant_search",
query,
params: {
hitsPerPage: 5,
highlightPreTag: "<mark>",
highlightPostTag: "</mark>",
},
},
],
});
},
getItemUrl({ item }) {
return item.url;
},
},
];
},
});
}
render() {
const { autocompleteState } = this.state;
return (
<div className="aa-Autocomplete" {...this.autocomplete?.getRootProps({})}>
<form
className="aa-Form"
{...this.autocomplete?.getFormProps({
inputElement: this.inputRef.current,
})}
>
<div className="aa-InputWrapperPrefix">
<label
className="aa-Label"
{...this.autocomplete?.getLabelProps({})}
>
Search
</label>
</div>
<div className="aa-InputWrapper">
<input
className="aa-Input"
ref={this.inputRef}
{...this.autocomplete?.getInputProps({})}
/>componentDidUpdate()
</div>
</form>
<div className="aa-Panel" {...this.autocomplete?.getPanelProps({})}>
{autocompleteState.isOpen &&
autocompleteState.collections.map((collection, index) => {
const { source, items } = collection;
return (
<div key={`source-${index}`} className="aa-Source">
{items.length > 0 && (
<ul
className="aa-List"
{...this.autocomplete?.getListProps()}
>
{items.map((item) => (
<li
key={item.objectID}
className="aa-Item"
{...this.autocomplete?.getItemProps({
item,
source,
})}
>
{item.name}
</li>
))}
</ul>
)}
</div>
);
})}
</div>
</div>
);
}
}
export default AutocompleteClass;
and the sandbox of the same version, I also tried using componentDidUpdate() but no luck, any lead where I did wrong would be much appreciated thank you :)
Ok, dont know why you need it made into class component but here you go:
import { createAutocomplete } from "#algolia/autocomplete-core";
import { getAlgoliaResults } from "#algolia/autocomplete-preset-algolia";
import algoliasearch from "algoliasearch/lite";
import React from "react";
const searchClient = algoliasearch(
"latency",
"6be0576ff61c053d5f9a3225e2a90f76"
);
// let autocomplete;
class AutocompleteClass extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
autocompleteState: {},
query: '',
};
this.autocomplete = createAutocomplete({
onStateChange: this.onChange,
getSources() {
return [
{
sourceId: "products",
getItems({ query }) {
console.log('getting query', query)
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: "instant_search",
query,
params: {
hitsPerPage: 5,
highlightPreTag: "<mark>",
highlightPostTag: "</mark>"
}
}
]
});
},
getItemUrl({ item }) {
return item.url;
}
}
];
}
});
}
onChange = ({ state }) => {
console.log(state)
this.setState({ autocompleteState: state, query: state.query });
}
render() {
const { autocompleteState } = this.state;
return (
<div className="aa-Autocomplete" {...this.autocomplete?.getRootProps({})}>
<form
className="aa-Form"
{...this.autocomplete?.getFormProps({
inputElement: this.state.query
})}
>
<div className="aa-InputWrapperPrefix">
<label
className="aa-Label"
{...this.autocomplete?.getLabelProps({})}
>
Search
</label>
</div>
<div className="aa-InputWrapper">
<input
className="aa-Input"
value={this.state.query}
{...this.autocomplete?.getInputProps({})}
/>
</div>
</form>
<div className="aa-Panel" {...this.autocomplete?.getPanelProps({})}>
{autocompleteState.isOpen &&
autocompleteState.collections.map((collection, index) => {
const { source, items } = collection;
return (
<div key={`source-${index}`} className="aa-Source">
{items.length > 0 && (
<ul
className="aa-List"
{...this.autocomplete?.getListProps()}
>
{items.map((item) => (
<li
key={item.objectID}
className="aa-Item"
{...this.autocomplete?.getItemProps({
item,
source
})}
>
{item.name}
</li>
))}
</ul>
)}
</div>
);
})}
</div>
</div>
);
}
}
export default AutocompleteClass;
Anyway the componentDidMount is called only once, and because of ref object is undefined it just returned from it.
Also messing with this in class components is quite a bad idea (that is why func components are recommended)
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>
);
}
}
Front End - Front End
Upon clicking the star, I want to update the state of nested object, with the new rating value of star.
I tried many things but it didnt work as states are immutable.
Nested State
Can some upon please suggest how can I update the value in nested object
onStarClicked = (kTypName, subItemId1, newRating) => {
//console.log(subItemId.split("_"));
let evaluation = subItemId1.split("_")[0];
let subItemId = subItemId1.split("_")[1];
console.log(subItemId);
const r = { ...this.state.ratings };
let kT = r.knowledgeTypes;
let sub = '', kTN = '', kIN = '';
kT.map(knowledgeType => {
//console.log(knowledgeType.knowledgeTypeId);
knowledgeType.knowledgeItems.map(knowledgeItem => {
//console.log(knowledgeItem.knowledgeItemId);
knowledgeItem.subItems.map(knowledgeSubItem => {
//console.log(knowledgeSubItem.subItemId);
if (subItemId === knowledgeSubItem.subItemId) {
kTN = knowledgeType.knowledgeTypeName;
kIN = knowledgeItem.knowledgeItemName;
sub = knowledgeSubItem;
if (evaluation === "self") {
sub.evaluation.self.rating = newRating;
}
else if (evaluation === "evaluator") {
sub.evaluation.evaluator.rating = newRating;
}
//alert(evaluation + subItemId + ' ' + newRating);
//return;
}
})
})
});
this.setState({
...this.state,
ratings: {
...this.state.ratings,
knowledgeTypes: [
...this.state.ratings.knowledgeTypes,
this.state.ratings.knowledgeTypes.filter(kt => kt.knowledgeTypeName !== kTN),
{
...this.state.ratings.knowledgeTypes.knowledgeItems.
filter(ki => ki.knowledgeItemName !== kIN),
knowledgeItems: {
...this.state.ratings.knowledgeTypes.knowledgeItems.subItems.
filter(si => si.subItemId !== subItemId),
sub
}
}]
}
});
}
You basically have to create a new empty array of knowledgeTypes and use the current state to find which item of the state you need to change using Object.keys/map/filter functions.
You'd use the current state in a variable and modify that variable only. You'd likely not mess with the actual state object in any way.
After you have done that, simply append it to the empty array. Then you can setState() the new array to the actual state property.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
financialYear: "2019-20",
quarter: "Q1",
isCurrentQuarter: true,
knowledgeTypes: [
{
knowledgeTypeName: "Technology",
knowledgeItems: [
{
knowledgeItemName: "Java",
subItems: [
{
subItemId: "2",
subItemName: "Collections",
evaluation: {
self: {
ntnet: "Joe",
rating: 1,
isEditable: true
}
}
}
]
}
]
}
]
};
}
handleClick = e => {
const { knowledgeTypes } = this.state;
// transformation
const itemToChange = knowledgeTypes.map(item => {
if (item.knowledgeTypeName === "Technology") {
return item;
}
});
const currItems = itemToChange[0].knowledgeItems[0].subItems;
const subItem = currItems.map(item => {
if (item.subItemId === "2") {
return item;
}
});
const person = subItem[0].evaluation;
person.self.rating = 55; //change
const newKnowledgeTypes = [];
knowledgeTypes.map(item => {
if (item.knowledgeTypeName === "Technology") {
newKnowledgeTypes.push(itemToChange);
}
newKnowledgeTypes.push(item);
});
this.setState({
knowledgeTypes: newKnowledgeTypes
});
console.log(this.state);
};
render() {
return (
<div>
MyComponent
<button onClick={this.handleClick}>Hello</button>
</div>
);
}
}
The sandbox can be found on https://codesandbox.io/s/musing-dew-8r2vk.
Note: It is advisable you do not use nested state objects because state objects are something more lightweight so that they do not have performance considerations.
import React, { Component } from 'react';
import Auxilary from '../../../hoc/Auxilary/auxilary';
import KnowledgeItems from '../KnowledgeItems/KnowledgeItems';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
import knowledge from '../../../assests/staticdata.json';
import './QuarterLog.css';
class QuarterLog extends Component {
constructor() {
super();
this.state = {
"financialYear": "",
"quarter": "",
"isCurrentQuarter": "",
"knowledgeTypes": []
}
}
onStarClicked = (kTypName, kItemName, subItemIdName, newRating) => {
let evaluation = subItemIdName.split("_")[0];
let subItemId = subItemIdName.split("_")[1];
const { knowledgeTypes } = this.state;
// transformation
let knowledgeTypeToChange = knowledgeTypes.map(kType => {
if (kType.knowledgeTypeName === kTypName) {
return kType;
}
});
knowledgeTypeToChange = knowledgeTypeToChange.filter(function (element) {
return element !== undefined;
});
console.log(knowledgeTypeToChange[0]);
let knowledgeItemToChange = knowledgeTypeToChange[0].knowledgeItems.map(item => {
if (item.knowledgeItemName === kItemName) {
return item;
}
});
knowledgeItemToChange = knowledgeItemToChange.filter(function (element) {
return element !== undefined;
});
let knowledgeSubItem = knowledgeItemToChange[0].subItems.map(subItem => {
if (subItem.subItemId === subItemId) {
return subItem;
}
});
knowledgeSubItem = knowledgeSubItem.filter(function (element) {
return element !== undefined;
});
console.log(knowledgeSubItem);
let personEvaluations = knowledgeSubItem[0].evaluation;
if (evaluation === "self") {
personEvaluations.self.rating = newRating.toString(); //change
}
else if (evaluation === "evaluator") {
personEvaluations.evaluator.rating = newRating.toString(); //change
}
const newKnowledgeTypes = [];
knowledgeTypes.map(item => {
if (item.knowledgeTypeName === kTypName) {
newKnowledgeTypes.push(knowledgeTypeToChange[0]);
}
else
newKnowledgeTypes.push(item);
});
this.setState({
knowledgeTypes: newKnowledgeTypes
});
console.log(this.state);
}
componentDidMount() {
// TODO: remove staticdata.js and call REST API and set the response in state
this.setState({
...this.state,
"financialYear": knowledge.financialYear,
"quarter": knowledge.quarter,
"isCurrentQuarter": knowledge.isCurrentQuarter,
"knowledgeTypes": knowledge.knowledgeTypes
})
}
onSubmitRatings = () => {
console.log(this.state);
}
render() {
let data = knowledge; //remove this code, once REST API is implemented
const posts = this.state.knowledgeTypes.map(knowledgeType => {
return (
<Tab key={knowledgeType.knowledgeTypeName} eventKey={knowledgeType.knowledgeTypeName}
title={knowledgeType.knowledgeTypeName}>
<KnowledgeItems
kTypeName={knowledgeType.knowledgeTypeName}
kItems={knowledgeType.knowledgeItems}
ratings={this.state.ratings}
onstarclicked={this.onStarClicked}
/>
</Tab>)
});
return (
<Auxilary>
<div className="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<div><h1>Financial Year : {data.financialYear}</h1></div>
<div><h2>Quarter : {data.quarter}</h2></div>
</div>
<div>
<Tabs defaultActiveKey="Domain" id="uncontrolled-tab-example">
{posts}
</Tabs>
</div>
<button onClick={this.onSubmitRatings}> Submit </button>
</Auxilary>
);
}
}
export default QuarterLog;
I am trying to make filter navigation and want to go back to previous state or trigger function to get the data from another API.
On click of this state, I should be able to clear the filter to return the response from another API.
To understand it completely, please look at the sample App I have created below
Stackblitz : https://stackblitz.com/edit/react-3bpotn
Below is the component
class Playground extends Component {
constructor(props) {
super(props);
this.state = {
selectedLanguage: 'All', // default state
repos: null
};
this.updateLanguage = this.updateLanguage.bind(this);
this.updateLanguagenew = this.updateLanguagenew.bind(this);
}
componentDidMount() {
this.updateLanguage(this.state.selectedLanguage);
}
updateLanguage(lang) {
this.setState({
selectedLanguage: lang,
repos: null
});
fetchPopularRepos(lang).then(
function (repos) {
this.setState(function () {
return { repos: repos };
});
}.bind(this)
);
}
updateLanguagenew(lang) {
if (lang === 'All') {
this.updateLanguage(lang);
return;
}
this.setState({
selectedLanguage: lang,
repos: null
});
fetchPopularReposUpdated(lang).then(
function (repos) {
this.setState(function () {
return { repos: repos };
});
}.bind(this)
);
}
render() {
return (
<div>
<div>
This is the current state : <strong style={{padding: '10px',color:'red'}}>{this.state.selectedLanguage}</strong>
</div>
<div style={{padding: '10px'}}>
On click of above state I should be able to trigger this function <strong>(updateLanguage)</strong> again to clear the filter and load data from this API
</div>
<p>Click the below options</p>
<SelectLanguage
selectedLanguage={this.state.selectedLanguage}
onSelect={this.updateLanguagenew}
/>
{//don't call it until repos are loaded
!this.state.repos ? (
<div>Loading</div>
) : (
<RepoGrid repos={this.state.repos} />
)}
</div>
);
}
}
SelectLanguage component mapping for filter options:
class SelectLanguage extends Component {
constructor(props) {
super(props);
this.state = {
searchInput: '',
};
}
filterItems = () => {
let result = [];
const { searchInput } = this.state;
const languages = [ {
"options": [
{
"catgeory_name": "Sigma",
"category_id": "755"
},
{
"catgeory_name": "Footner",
"category_id": "611"
}
]
}
];
const filterbrandsnew = languages;
let value
if (filterbrandsnew) {
value = filterbrandsnew[0].options.map(({catgeory_name})=>catgeory_name);
console.log (value);
}
const brand = value;
if (searchInput) {
result = this.elementContainsSearchString(searchInput, brand);
} else {
result = brand || [];
}
return result;
}
render() {
const filteredList = this.filterItems();
return (
<div className="filter-options">
<ul className="languages">
{filteredList.map(lang => (
<li
className={lang === this.props.selectedLanguage ? 'selected' : ''}
onClick={this.props.onSelect.bind(null, lang)}
key={lang}
>
{lang}
</li>
))}
</ul>
</div>
);
}
}
Note: This is having the current state {this.state.selectedLanguage}, on click of this I should be able to trigger this function. updateLanguage
The way you are doing set state is not correct
Change
fetchPopularRepos(lang).then(
function (repos) {
this.setState(function () {
return { repos: repos };
});
}.bind(this)
);
To
fetchPopularRepos(lang).then(
function (repos) {
this.setState({
repos: repos
});
}.bind(this)
);
Also Change
fetchPopularReposUpdated(lang).then(
function (repos) {
this.setState(function () {
return { repos: repos };
});
}.bind(this)
);
To
fetchPopularReposUpdated(lang).then(
function (repos) {
this.setState({
repos: repos
});
}.bind(this)
);
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;