Please need help paginating the results of information in an external API (pokeapi.co) I can fetch all the items, I have limited the answers to one hundred units and now I want to page ten out of ten per page but have the following error , when I click pagination links to switch pages and the items still don't appear as paginated.
Please, can anyone help me? Thank you in advance.
import React, { Component } from 'react';
import axios from 'axios';
import Pagination from 'react-js-pagination';
import PokemonCard from './PokemonCard';
require ('bootstrap-less/bootstrap/bootstrap.less');
export default class PolemonList extends Component {
constructor(props) {
super(props);
this.state = {
activePage: 1,
pageNumber: 10
};
}
handlePageChange(pageNumber) {
console.log(`active page is ${pageNumber}`);
this.setState({activePage: pageNumber});
}
state = {
url: 'https://pokeapi.co/api/v2/pokemon/?offset=0&limit=100',
pokemon: null
};
async componentDidMount() {
const res = await axios.get('https://pokeapi.co/api/v2/pokemon/?offset=0&limit=100');
this.setState({ pokemon: res.data['results'] })
}
render() {
return(
<React.Fragment>
{this.state.pokemon ? (
<div className="row">
{this.state.pokemon.map(pokemon => (
<PokemonCard
key={pokemon.name}
name={pokemon.name}
url={pokemon.url}
/>
))}
</div>
) : (
<h2>Loading Pokemon</h2>
)}
<hr></hr>
<div className="row">
<div className="col-12 text-center">
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={8}
totalItemsCount={100}
pageRangeDisplayed={10}
onChange={this.handlePageChange}
/>
</div>
</div>
</React.Fragment>
);
}
}
Error below:
this.setState is not a function in line 21 of the code that I list.
Your code is valid, so there must be an error with your build/project setup or some other issue.
Related
i am new to react and have been trying this for a long time without any success. Maybe someone could look through and determine the mistate i am making. here is my code.
I have the App.js file with a route to services page where i want to fecth and display data divs with services from a mysql database with react and JSX.
import React, { Component } from "react";
import { BrowserRouter } from "react-router-dom";
import Footer from "./Footer";
import Header from "./Header";
import axios from "axios";
class Services extends React.Component {
constructor(props) {
super(props);
this.state = {
services: [],
};
}
componentDidMount() {
axios
.get("http://localhost:5000/services")
.then((response) => this.setState({ services: response.data }));
}
render() {
var { services } = this.state;
return (
<div>
<div className="row">
<BrowserRouter>
<Header></Header>
</BrowserRouter>
<div className="Services">
<br></br>
<br></br>
<br></br>
</div>
<div className="row">
<h1 className="text-center title">Our Services</h1>
<p className="p-3 text-left">
Quickly get help for your issue by selcting the service that
matches your issues. You can always describe your issue if it does
not match any of our services and you only pay when the issue has
been resolved.
</p>
<hr></hr>
{services}
</div>
</div>
<BrowserRouter>
<Footer></Footer>
</BrowserRouter>
</div>
);
}
}
export default Services;
import React from "react";
import { BrowserRouter } from "react-router-dom";
import axios from "axios";
class Services extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/posts").then(response => {
console.log(response);
this.setState({ data: response.data });
});
}
render() {
let services_data = [];
this.state.data.forEach((res, i) => {
services_data.push(
<ul key={res.i}>
<li>{res.id}</li>
<li>{res.title}</li>
<li>{res.body}</li>
</ul>
);
});
return (
<div>
<div className="row">
<BrowserRouter>Header</BrowserRouter>
<div className="Services" />
<div className="row">
<h1 className="text-center title">Our Services</h1>
<p className="p-3 text-left">
Quickly get help for your issue by selcting the service that
matches your issues. You can always describe your issue if it does
not match any of our services and you only pay when the issue has
been resolved.
</p>
<hr />
{services_data}
</div>
</div>
<BrowserRouter>Footer</BrowserRouter>
</div>
);
}
}
export default Services;
The above code is working fine and split the method like this.
I am following the current tutorial:
Youtube tutorial at 12:51 mins.
I expect to see bunch of posts on my screen but my screen remains blank.
It appears I have followed everything told in the tutorial.
import React, { Component } from 'react';
class Posts extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentWillMount() {
fetch('https://jsonplaceholder.typicode.posts')
.then(res => res.json())
.then(data => this.setState({posts: data}))
}
render() {
const postItems = this.state.posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
));
return (
<div>
<h1>Posts</h1>
{ postItems }
</div>
);
}
}
export default Posts;
and
import React, { Component } from 'react';
import './App.css';
import Posts from './components/Posts'
class App extends Component {
render() {
return (
<div className="App">
<Posts />
</div>
);
}
}
export default App;
My browser screen remains blank and I do not see any errors on console.
What am I missing ?
Don't know about the tutorial but it looks outdated...
Here is your App.js (parent component):
import React, { Component } from 'react';
import Posts from './Posts';
export default class App extends Component {
state = { posts: [] };
//fetch the posts and store them in the state
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(posts => this.setState({ posts }))
.catch(error => console.log(error));
}
render() {
return (
<div>
{/* pass the state (posts) as props to Posts */}
<Posts posts={this.state.posts} />
</div>
);
}
}
Here is your Posts.js:
import React from 'react';
// No need for a class based comp
// destructure the props and you have all your data
const Posts = ({ posts }) => (
<div>
{posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
<hr />
</div>
))}
</div>
);
export default Posts;
Live Demo: https://jsfiddle.net/ctszdue9/7/
Try putting side effect/ api call inside
componentDidMount() { }
Change URL
https://jsonplaceholder.typicode.posts/
TO
https://jsonplaceholder.typicode.com/posts
I've been looking for about 2 hours into why I am not displaying any of the information to the page. I've console logged my response from a simple random quote api and it shows, Author: and Quote: in the console, however these are not appearing in my fields, All I am seeing is the button.
import React, { Component } from 'react';
import QuoteMachine from './Quotemachine';
const END_POINT = 'https://random-quote-
generator.herokuapp.com/api/quotes/random';
class App extends Component {
constructor(props) {
super(props);
this.state = {
quote: {
text: '',
author: ''
}
}
}
getQuote() {
fetch(END_POINT)
.then(response => response.json())
.then(response => {
this.setState = ({
quote: response
});
console.log(response);
})
}
componentDidMount() {
this.getQuote();
}
render() {
return (
<div className="App">
<div className="container">
<QuoteMachine quote= {this.state.quote} />
<button id="new-quote" className="primary-color-
background" onClick={() => this.getQuote()}>New quote</button>
</div>
</div>
);
}
}
export default App;
And then here is my Quotemachine.js
import React from 'react'
import PropTypes from 'prop-types';
const QuoteMachine = (props) => {
return (
<div className="quote-box">
<div className="text">
<span>{props.quote.text}</span>
</div>
<div className="author">
<span >{props.quote.author}</span>
</div>
</div>
);
};
QuoteMachine.propTypes = {
quote: PropTypes.object.isRequired
};
export default QuoteMachine;
It is only displaying the button, but the console.log shows
Object
author:
"Thomas Henry Huxley (1825-1895)"
quote:
"Try to learn something about everything and everything about something."
proto
:
Object
Install React Developer Tools plugin and check if your state is changing after the API call
I'm following this online tutorial on using Fetch to consume API data; I was able to get the application to Fetch data using the JSON url provided in the tutorial. However, I made some modifications to the code and attempted to fetch data from a different JSON file and got an error:
Here is the code:
import React, { Component } from 'react';
import {render} from "react-dom";
import Navbar from '../components/Navbar.jsx';
import Footer from '../components/Footer.jsx';
import './ClientInfo.css';
class ClientInfo extends Component {
constructor(){
super();
this.state= {
titles: []
};
}
componentWillMount(){
fetch('https://jsonplaceholder.typicode.com/todos')
.then(results => {
return results.json();
}).then(data => {
let titles = data.results.map((til) => {
return(
<div key={til.results}>
<p>{til.title} </p>
</div>
)
})
this.setState({titles: titles});
console.log("state", this.state.titles);
})
}
render() {
return (
<div>
<Navbar />
<div className="container">
<div className="clientContainer">
{this.state.titles}
</div>
</div>
<Footer />
</div>
);
}
}
export default ClientInfo
The error occurs at this line:let titles = data.results.map((til) => {. could I get some help as what am doing wrong?
data.results - not array. Array data.map
I am really new to React, so I am trying to build a Pokemon app. My main goal is to build the list of 20 pokemon, and detail box which when clicked on Pokemon from the list should display chosen pokemon details, pictures etc.
import React, { Component } from 'react';
import './styles/App.css';
class App extends Component{
render(){
return <div className="App">
<h1> Pokedex! </h1>
<PokemonList/>
<PokemonDetail/>
</div>;
}
}
class Pokemon extends Component {
render(){
const {pokemon,id} = this.props;
return <div className="pokemon--species">
<button className="pokemon--species--container">
<div className="pokemon--species--sprite">
<img src={`https://pokeapi.co/media/sprites/pokemon/${id}.png`} />
</div>
<div className="pokemon--species--name">{id} {pokemon.name} {pokemon.url} </div>
</button>
</div>;
}
}
class PokemonDetail extends Component {
render(){
const {pokemon, id} = this.props;
return <div className="pokemon--species">
<button className="pokemon--species--container">
<div className="pokemon--species--sprite">
<img src={`https://pokeapi.co/media/sprites/pokemon/${id}.png`} />
</div>
<div className="pokemon--species--name">{id}</div>
<p>Attack:72</p>
<p>Defense:23</p>
<p>Health:99</p>
</button>
</div>;
}
}
class PokemonList extends Component{
constructor(props){
super(props);
this.state = {
species : [],
fetched : false,
loading : false,
};
}
componentWillMount(){
this.setState({
loading : true
});
fetch('https://pokeapi.co/api/v2/pokemon?limit=20').then(res=>res.json())
.then(response=>{
this.setState({
species : response.results,
loading : true,
fetched : true
});
});
}
render(){
const {fetched, loading, species} = this.state;
let content ;
if(fetched){
content = <div className="pokemon--species--list">{
species.map((pokemon,index) => <Pokemon key={pokemon.name} id={index+1} pokemon={pokemon}/>)
}
</div>;
}else if(loading && !fetched){
content = <p> Loading ...</p>;
}
else{
content = <div/>;
}
return <div className="container">
{content}
</div>;
}
}
export default App;
I know, there is much to do there, but first I want to understand how to pass ID to pokemondetails class.
Have a look at react-router and how to pass parameters to components associated with routes. Basically, you could have two routes that would render following components PokemonList and PokemonDetail. Redirect user from the PokemonList to PokemonDetail and append pokemonId to the url ( e.g "/details/23").
After redirection 'PokemonDetail' component would be rendered and pokemonId would be available in the component.
const App = () => (
<Router>
<div>
...
<Route exact path="/" component={PokemonList}/>
<Route path="/details/:pokemonId" component={PokemonDetail}/>
</div>
</Router>
)
// access pokemonId
class PokemonDetail extends Component{
render() {
return (
<div>
<h2>{this.props.params.pokemonId}</h2>
</div>
)
}
}