I have this simple react app, where I fetch the Flickr public feed. So, I can scroll to the end of the page and new content is going to show. So I would like to scroll until there is nothing else new, and the app stops trying to load more content, because it has reached the last item of the list, which is not happening if I try to scroll (you can see that on the loading message). How can I fix this?
Check the code below:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import $ from "jquery";
import PhotoListItem from "./photoListItem";
import "./photoApp.css";
export default class PhotoApp extends Component {
constructor(props) {
super(props);
this.state = {
photoList: [],
searchTerm: "cyanotype",
items: 8,
loadingState: false,
loadingMessage: ""
};
}
componentDidMount() {
this.getPhotoList();
this.onInfiniteScroll();
}
/* get data from Flickr public feed */
getPhotoList = () => {
const flickrApiPoint =
"https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?&tags=" +
this.state.searchTerm;
try {
$.ajax({
url: flickrApiPoint,
dataType: "jsonp",
data: { format: "json" },
success: function(data) {
this.setState({ photoList: data.items });
}.bind(this)
});
} catch (err) {
console.log(err);
}
};
/* code for infinite scroll */
onInfiniteScroll = () => {
this.refs.iScroll.addEventListener("scroll", () => {
if (
this.refs.iScroll.scrollTop + this.refs.iScroll.clientHeight >=
this.refs.iScroll.scrollHeight - 20
) {
this.loadMoreItems();
}
});
};
/* code for infinite scroll */
loadMoreItems = () => {
if (this.state.loadingState) {
return;
}
this.setState({
loadingState: true,
loadingMessage: "Loading photos..."
});
setTimeout(() => {
this.setState(prevState => ({
items: prevState.items + 8,
loadingState: false,
loadingMessage: "No more photos to show."
}));
}, 1000);
};
render() {
console.log(this.state.photoList)
return (
<div className="appContainer" ref="iScroll">
<div className="appHeader">
<h1 className="headerTitle">
Welcome to Flickr Alternative Photography Feed!
</h1>
</div>
<div className="gridContainer">
{this.state.photoList
.slice(0, this.state.items)
.map((photo, index) => {
const author = photo.author.split(/"/)[1];
const authorLink = photo.description.split(/"/)[1];
const description = photo.description.split(/"/)[13];
return (
<PhotoListItem
key={index}
url={photo.media.m}
photoLink={photo.link}
title={photo.title}
author={author}
authorLink={authorLink}
description={description}
tags={photo.tags}
/>
);
})}
</div>
<React.Fragment>
{this.state.loadingState ? (
<p className="loading">{this.state.loadingMessage}</p>
) : (
<p className="loading">{this.state.loadingMessage}</p>
)}
</React.Fragment>
</div>
);
}
}
LIVE EXAMPLE HERE
Thank you!
You could check if the item that you've loaded exceeds your items in your ajax request
/* code for infinite scroll */
loadMoreItems = () => {
// hasMore = data.items.length (you may want to rename this more appropriately)
if (this.state.loadingState || (this.state.items > this.state.hasMore)) {
// Do not load if there's no more items
return;
}
...
Your onInfiniteScroll doesn't have any code right now that checks whether it should load more items, it just blindly does. So: at the end of getPhotoList you probably want to check whether that's the last page of results and if so, do a setState({ exhausted: true }) or something similar, so you can check that value in your onInfiniteScroll and not do anything if you see this.state.exhausted === true.
Related
I am using MERN stack and Redux. I have created an array in the state 'comments' which is updated via the clickHandler function with elements from the global state (accessed via props). When i try to show the contents of the array in the render i just get the length of it. How would i show the properties of the elements for example title.
import React, { Component } from "react";
import PropTypes from "prop-types";
import GoogleSearch from "./GoogleSearch";
import { connect } from "react-redux";
import { fetchSubjects } from "../../actions/subject";
import { fetchComments } from "../../actions/comment";
import store from "../../store";
class Subject extends Component {
// on loading the subjects and comments
// are fetched from the database
componentDidMount() {
this.props.fetchSubjects();
this.props.fetchComments();
}
constructor(props) {
super(props);
this.state = {
// set inital state for subjects description
// and summary to invisible
viewDesription: -1,
viewSummary: -1,
comments: [],
};
}
componentWillReceiveProps(nextProps) {
// new subject and comments are added to the top
if (nextProps.newPost) {
this.props.subjects.unshift(nextProps.newPost);
}
if (nextProps.newPost) {
this.props.comments.unshift(nextProps.newPost);
}
}
clickHandler = (id) => {
// when a subject title is clicked pass in its id
// and make the desciption visible
const { viewDescription } = this.state;
this.setState({ viewDescription: viewDescription === id ? -1 : id });
// clear the existing comments in state
this.setState({
comments: [],
});
// loop through the comment items in the global state
// and add any with the same subjects id passed in to the array
var i;
for (i = 0; i < this.props.comments.length; i++) {
if (this.props.comments[i].subject == id) {
console.log(this.props.comments[i]);
this.setState({
comments: this.state.comments.unshift(this.props.comments[i]),
});
}
} // set local storage to the id for the subject that has been clicked
localStorage.setItem("passedSubject", id);
};
// hovering on and off subjects toggles the visibility of the summary
hoverHandler = (id) => {
this.setState({ viewSummary: id });
};
hoverOffHandler = () => {
this.setState({ viewSummary: -1 });
};
render() {
const subjectItems = this.props.subjects.map((subject) => {
// if the state equals the id set to visible if not set to invisible
var view = this.state.viewDescription === subject._id ? "" : "none";
var hover = this.state.viewSummary === subject._id ? "" : "none";
var comments = this.state.comments;
return (
<div key={subject._id}>
<div
className="subjectTitle"
onClick={() => this.clickHandler(subject._id)}
onMouseEnter={() => this.hoverHandler(subject._id)}
onMouseLeave={() => this.hoverOffHandler()}
>
<p className="title">{subject.title}</p>
<p className="rating">Rating: {subject.rating}</p>
<p className="summary" style={{ display: hover }}>
{subject.summary}
</p>
</div>
<div className="subjectBody " style={{ display: view }}>
<div className="subjectAuthor">
<p className="author">
Subject created by: {subject.author} on {subject.date}
</p>
<a href="">
<div className="buttonRateSubject">RATE SUBJECT</div>
</a>
</div>
<div className="subjectDescription">
<p className="description">{subject.description}</p>
</div>
<div className="subjectLinks">Links:</div>
<div className="subjectComments">
<p>Comments:</p>
{/* ************HERE*********** */}
<p>{comments}</p>
{/* ********************************* */}
<a href="/addcomment">
<div className="buttonAddComment">ADD COMMENT</div>
</a>
</div>
</div>
</div>
);
});
return (
<div id="Subject">
<GoogleSearch />
{subjectItems}
</div>
);
}
}
Subject.propTypes = {
fetchSubjects: PropTypes.func.isRequired,
fetchComments: PropTypes.func.isRequired,
subjects: PropTypes.array.isRequired,
comments: PropTypes.array.isRequired,
newPost: PropTypes.object,
};
const mapStateToProps = (state) => ({
subjects: state.subjects.items,
newSubject: state.subjects.item,
comments: state.comments.items,
newComment: state.comments.item,
});
// export default Subject;
export default connect(mapStateToProps, { fetchSubjects, fetchComments })(
Subject,
Comment
);
I think I know your problem. You want to render items of an array.
Let me just give you a short overview.
Javascript:
this.setState({
comments: data
});
render (){
return (
<div>
{ this.state.comments.map(c=> <div>{c.body}</div> ) }
</div>
)
}
Thanks guys, i changed the for loop in the clickHandler to this which now has data rendering, it didn't like objects in the array for some reason.
var temp = [];
for (i = 0; i < this.props.comments.length; i++) {
if (this.props.comments[i].subject == id) {
console.log(this.props.comments[i]);
temp.unshift(this.props.comments[i].comment);
temp.unshift(this.props.comments[i].title);
}
}
this.setState({
comments: temp,
});
I'd like to know why I'm getting a 500 error when trying to upload photos to the DB. I have a feeling my controller's messed up as well as my axios call in my React code. Pastebin's below. If you need more information please let me know.
https://pastebin.com/Pv1eigFK
here is App.js
import React, {Component} from 'react';
import axios from 'axios';
import Feed from '../components/Feed/Feed';
import Upload from '../components/Upload/Upload';
import ImagePreview from './ImagePreview/ImagePreview';
class App extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
previewImgURL: '',
imgPrev: false,
success: false,
progress: 0,
imageChosen: false,
pictures: [],
hideForm: true,
};
this.imageUpload = this.imageUpload.bind(this);
this.submitImageAndRedirect = this.submitImageAndRedirect.bind(this);
this.postIsClicked = this.postIsClicked.bind(this);
this.feedView = this.feedView.bind(this);
}
imagePreview(newPostImageBool) {
this.setState({imgPrev: newPostImageBool});
if (this.state.selectedFile === null) {
alert("can't preview a picture on this because it's empty");
this.setState({imgPrev: false});
}
};
closeModal() {
this.setState({imgPrev: false});
};
imageUpload(e) {
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
selectedFile: file,
previewImgURL: reader.result,
pictures: [reader.result]
}, () => {
console.log(this.state.pictures);
})
};
if (file) reader.readAsDataURL(file); // Allows user to preview image uploaded
this.setState(() => ({file}));
this.setState({success: true, imageChosen: true});
}
submitImageAndRedirect() {
// e.preventDefault();
let picUrl = this.state.previewImgURL;
axios.post('/home', {
body: picUrl
}).then(response => {
// console
console.log(response);
// set state
this.setState({
pictures: [picUrl, response.data]
});
});
console.log("submitImageAndRedirect() triggered");
}
postIsClicked(e) {
console.log("postIsClicked(e) triggered");
if (e.target.value === "Yes") {
this.feedView();
this.submitImageAndRedirect();
console.log(`Yes has been clicked... inside Yes if block`);
} else {
alert("No clicked");
}
}
feedView() {
this.setState({hideForm: false}, () => console.log(this.state.hideForm));
}
render() {
return (
<div className="feed-wrapper">
{this.state.success ?
<div className="alert alert-success">
<strong>Chosen image is successful!
Now click Preview and make sure that's the one you want to upload!</strong>
</div> : null}
{this.state.hideForm ?
<form onSubmit={this.submitImageAndRedirect}>
<div className="inputWrapper">
<input
id="new_post_image"
name="post_image"
className="button is-success is-outlined"
type="file"
style={{display: 'none'}}
onChange={this.imageUpload}
accept="image/*"
/>
<Upload/>
<br/>
{
this.state.imageChosen ?
<div className="uploaded-pics">
<ImagePreview src={this.state.previewImgURL} onClick={this.postIsClicked}/>
</div> : null
}
</div>
</form>
: null
}
{!this.state.hideForm ?
this.state.pictures.map(post => {
return <Feed src={post} />
})
:null}
</div>
);
}
}
export default App;
Here's my controller:
<?php
namespace App\Http\Controllers;
use App\User;
use App\PostPictures;
use Illuminate\Http\Request;
class PostPicturesController extends Controller
{
public function create(Request $request, PostPictures $postPicture) {
$uploadPic = $postPicture->user()->postPictures->create([
'body' => $request->body
]);
return response()->json($postPicture->with('user')->find($uploadPic->id));
}
}
error in console:
POST http://mywebsite.test/home 500 (Internal Server Error)
error in Laravel logs:
[2019-10-06 16:25:56] local.ERROR: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mywebsite.post_pictures' doesn't exist (SQL: select * from `post_pictures` where `post_pictures`.`user_id` = 5 and `post_pictures`.`user_id` is not null) {"userId":5,"exception":"[object] (Illuminate\\Database\\QueryException(code: 42S02): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mywebsite.post_pictures' doesn't exist (SQL: select * from `post_pictures` where `post_pictures`.`user_id` = 5 and `post_pictures`.`user_id` is not null) at /Users/garenvartanian/workstation/mywebsite/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: 42S02): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mywebsite.post_pictures' doesn't exist at /Users/garenvartanian/workstation/mywebsite/vendor/laravel/framework/src/Illuminate/Database/Connection.php:326)
[stacktrace]
The error said, laravel can not found you table post_pictures on mywebsite database.
Did you create the table?
if you don't please create a migration for make table:
https://laravel.com/docs/5.8/migrations
sometime you maybe wish make the model name is different with the table name on database.
You may need to add table name to model like :
class Flight extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'my_flights';
}
hope it help. Thanks
I am using React - Redux to display search results. I do not want to display all results and want to keep performance as good as possible.
This is how I get and display the results:
handleSubmit(event) {
event.preventDefault()
this.setState({
searchedOnce: true
})
const apiSearchURL = `/api/search/religion/${this.state.formValues.religion}/gender/${this.state.formValues.gender}`
get(apiSearchURL, { maxContentLength: 400 })
.then((searchResults) => {
this.props.dispatch(getSearchResults(searchResults))
})
}
...
...
render() {
const { users } = this.props
let map_usersList = users.data && users.data.map((userlist => (
<SearchResult key={userlist.id} {...userlist} />
)))
...
...
...
<ul>
{ this.state.searchedOnce
? map_usersList
: <SearchNoResult/>
}
</ul>
How can I display map_usersList - 5 items at a time with load more button and show a message "No more items" at the end when there are no more results ?.
I am using Redux. When the search results come up the state has all the results. I am thinking the first time the state should only have 5 items ? I have never worked with React/Redux so need some tips.
You can simply slice the users.data to display only the number of users you want to display at a time. Assuming that you want to display 5 more users on each click of a 'Load More' button, you can go by the following code:
constructor(){
this.state = {
....
pageNo: 1,
}
}
....
render() {
const { users } = this.props
let map_usersList = users.data && users.data.slice(0, this.state.pageNo * 5).map((userlist => (
<SearchResult key={userlist.id} {...userlist} />
)))
....
....
loadMoreClick() {
this.setState({
pageNo: this.state.pageNo + 1,
})
}
....
....
<ul>
{ this.state.searchedOnce
? map_usersList
: <SearchNoResult/>
}
{
this.state.pageNo * 5 >= 400 //(maxContentLength)
? 'No more items' : <LoadMoreButton />
}
</ul>
I'm building a component which proceeds according to the selections of the users. I have completed it successfully but facing some issues when trying to implement a back button to go back.
My code is like follows.
class ReportMainCat extends Component {
constructor(props) {
super(props);
this.state = {
postType: null,
}
this.changeType = this.changeType.bind(this);
this.report_next = this.report_next.bind(this);
};
report_next() {
if (this.state.postType == null) {
return <ReportFirst changeType={this.changeType}/>
}
else if (this.state.postType === 'sexual') {
return <ReportXContent changeType={this.changeType}/>
} else if (this.state.postType === 'selfharm') {
return <ReportThreatContent changeType={this.changeType}/>
}
}
changeType = (postType) => {
this.setState({postType})
this.setState({
showMainReportCats: false,
})
}
render() {
return (
<div className="top_of_overlay">
<div className="section_container text_align_center padding_10px">
<a className="">Report Category</a>
{this.report_next()}
</div>
</div>
)
}
}
I'm binding the postType value as follows.
class ReportXContent extends Component {
constructor(props) {
super(props);
this.state = {
postType: '',
}
};
textType(postType) {
this.props.changeType(postType);
}
render() {
return (
<div className="text_align_left">
<div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="nudity" onClick={this.textType.bind(this,'nudity')}/>
<a>Nudity or Pornography</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="minor" onClick={this.textType.bind(this,'minor')}/>
<a>Includes Minors</a>
</div>
</div>
<ReportButtons/>
</div>
)
}
}
My back button
<div>
<button className="float_right margin_left5px" onClick={this.props.back_report}>Back</button>
</div>
So basically what i'm trying to do is this.
Ex: If the user selects postType as sexual it will return the ReportXContent component. How can i return to the first page when the user clicks the back button.
Thanks.
You could implement the back button click handler like this in the ReportMainCat component:
handleBackClick() {
this.setState({ postType: null });
}
, and that would show the ReportFirst view again.
If you don't want the first view, but the last view, simply change your changeType implementation to save lastPostType to state like this:
changeType = (postType) => {
this.setState({
lastPostType: this.state.postType,
postType,
showMainReportCats: false,
});
}
Edit
If you want full history of changes - let's say if you want to implement a full back button history - you can simply rename lastPostType to postTypeHistory and implement it like a stack (like the browser history is):
changeType = (postType) => {
this.setState({
postTypeHistory: [...this.state.postTypeHistory, this.state.postType],
postType,
showMainReportCats: false,
});
}
handleBackClick() {
const { postTypeHistory } = this.state;
const postType = postTypeHistory.pop();
this.setState({
postType,
postTypeHistory,
});
}
Code Situation
I have a simple react app setup. The home component should be a image gallery with a masonry layout. I found this library: Bricks.js
I load the data (name, date, url to image) of the items from my api with fetch.
Here are some parts of my code in Home.js:
The constructor()
constructor() {
super();
this.state = {
galleryItems: []
};
this.instance = {}
}
This function loads the data of the items.
getItems(limit){
fetch('http://localhost:3000/api/posts/next/' + limit)
.then((response) => {
return response.json()
}).then((data) => {
this.setState({galleryItems: data});
})
}
I used the componentDidMount() function to load 5 items and create the Bricks.js instance.
componentDidMount(){
this.getItems(5)
//sizes for Brick.js
const sizes = [
{ columns: 5, gutter: 3 },
{ mq: '768px', columns: 2, gutter: 3 },
{ mq: '1024px', columns: 3, gutter: 3 }
]
//init instance
this.instance = Bricks({
container: '.gallery',
packed: 'packed',
sizes: sizes
})
this.instance.resize(true); //<-adds a resize event listener
if (this.state.galleryItems.length > 0) {
this.instance.pack() //<- This should create the masonry layout
}
}
And for loading more image I wrote this in the componentDidUpdate() function.
componentDidUpdate(){
if (this.state.galleryItems.length > 0) {
return this.instance.pack()
}
else{
return this.instance.update() //<- updates the layout
}
}
The render() function converts the data from the server to a <Item> which is just another component that creates a <img> element
render() {
const items = this.state.galleryItems.map((item, _id) => {
return <Item key={_id} url={this.state.url + item.url}></Item>
})
return (
<div>
Home Component
<div className="gallery">
{items}
</div>
</div>
);
}
Problem
If I open my app in firefox it works fine. But in chrome the images are just on top of each other. If I resize the window the masonry layout is created fine. I seems chrome is either too fast or slow.
What is wrong with my code that this can happen?