App crashes after refresh - reactjs

I have got a problem with my app. Everything is fine untill I press the refresh button. I assume it is happening because of some stuff is not ready to be rendered yet.
import React from 'react'
import { Meteor } from 'meteor/meteor'
import { createContainer } from 'meteor/react-meteor-data'
import { withRouter } from 'react-router'
import LeftNavbar from '../dashboard/LeftNavbar'
import UpperBar from '../dashboard/UpperBar'
import NewGreetingsForm from './NewGreetingsForm'
import ConfigureButtons from './ConfigureButtons'
import Fanpages from '../../../api/Fanpages.js'
import './Greetings.scss'
export class Greetings extends React.Component {
constructor (props) {
super(props)
this.fanpage = this.props.user.profile.fanpages
this.state = {
newGreetingsText: '',
newGreetingsCharCount: 0
}
}
componentDidMount () {
}
render () {
const currentFanpage = Fanpages.findOne({fanpageName: this.fanpage})
const currentGreeting = currentFanpage.fanpageInfo.fanpageInfo.config.greeting[0].text
return (
<div className='container page'>
<UpperBar title={'Konfiguracja fanpage / Zdefiniuj greetings'} />
<LeftNavbar />
<div className='main-content'>
<h4 id='main-title'>{this.fanpage}</h4>
<div className='container'>
<div className='row'>
<ConfigureButtons />
<div>
<h5 id='configure-content-right'>Zmień obecną informację</h5>
<NewGreetingsForm fanpageName={this.fanpage} placeholder={currentGreeting} />
</div>
</div>
</div>
</div>
</div>
)
}
}
export default withRouter(createContainer(() => ({
user: Meteor.user()
}), Greetings))
Any idea where I should move those variables from render method? So it works as it should after page refresh? Thanks a lot for any participation.

Assuming there's subscription management going on above this component you can just defend against the data not being ready:
render () {
const currentFanpage = Fanpages.findOne({fanpageName: this.fanpage});
if (!currentFanpage) {
return (
<div />
);
} else {
const currentGreeting = currentFanpage.fanpageInfo.config.greeting[0].text
return (
// your html
)
}
}
Better yet, have the parent component render a spinner until the subscription is .ready()
Update
You asked about using createContainer with withRouter. I don't normally use withRouter and I haven't tested this but it should go something like:
const container = () => {
const sub = Meteor.subscribe('mysub');
const loading = sub.ready();
const user = Meteor.user();
return { loading, user };
}
export default withRouter(container, Greetings))
The important thing being that the container have a loading key that's tied to the state of the subscription.
Container tutorial

Related

Why am i getting undefined on my variable?

I am practicing using axios in ReactJs where i have my App.js component which is in charge of fetching de data of my api using axios. This App.js renders a component that containt child components in it and one of the child component is my ImageList.js component where im rendering the list of images by mapping the array.
App.js:
import React, { Component } from 'react'
import SearchInput from './components/SearchInput'
import axios from 'axios';
import ImageList from './components/ImageList';
export default class App extends Component {
state = {images: []}
onSearchSubmit = async(entry) => {
const response = await axios.get(`https://pixabay.com/api/?key=29058457-42bf8a0bcd2bc1293e234b193&q=${entry}&image_type=photo`)
console.log(response.data.hits)
this.setState({images:response.data.hits});
}
render() {
return (
<div className='ui container' style={{marginTop:'30px'}}>
<SearchInput onSearchSubmit={this.onSearchSubmit}/>
We have {this.state.images.length} Images
<ImageList images={this.state.images}/>
</div>
)
}
}
ImageList.js:
import React from 'react'
const ImageList = (props) => {
const images = props.images.map((image) =>{
return <img key={props.id} src={image.webFormatURL} alt="image" />
});
return (
<div>{images}</div>
)
}
export default ImageList
The error is suposed to be at line 10:11 at ImageList.js
images is undefined

why is my component getting rendered once but then failing on refresh

i am working on small react assignment,
following is my component code. So my component is getting rendered once but then it just fails.i'll attach the screenshots too, can some one please explain what is happening?is there an error in the code or is it because of some rate limiting in API i am using?
import React from 'react'
const Menu = ({events}) => {
console.log(events);
return (
<div>
{events.map((event)=>{
return( <div key={event.category}>
<h3>{event.category}</h3>
</div>)
})}
</div>
)
}
export default Menu
code working image
error on same code pic
parent component code
import React,{useState,useEffect} from 'react';
import './App.css';
import Menu from './components/Menu';
function App() {
const [isLoading,setISLoading] = useState(true);
const[events,setEvents] = useState()
const getEvents = async()=>{
const response = await fetch('https://allevents.s3.amazonaws.com/tests/categories.json');
const eventsData =await response.json()
setISLoading(false);
setEvents(eventsData);
}
useEffect(()=>getEvents(),[]);
return (
isLoading?<h1>Loading...</h1>:<Menu events = {events}/>
);
}
export default App;
May be the parent component of Menu which is supplying events is not using any loading state. So when the component is mounted and starts making ajax calls, events is undefined. You need to put a condition over there like this:
import React from 'react'
const Menu = ({events}) => {
console.log(events);
return events ? (
<div>
{events.map((event)=>{
return( <div key={event.category}>
<h3>{event.category}</h3>
</div>)
})}
</div>
) : null
}
export default Menu

TypeError: robots.map is not a function

I keep getting this error: TypeError: robots.map is not a function.
I reviewed the code several times can't find the bug.
import React from 'react';
import Card from './Card';
// import { robots } from './robots';
const CardList = ({ robots }) => {
return(
<div>
{
robots.map((user, i) => {
return (
<Card
key={i}
id={robots[i].id}
name={robots[i].name}
email={robots[i].email}
/>
);
})
}
</div>
);
}
export default CardList;
App.js
import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';
class App extends Component {
constructor(){
super()
this.state = {
robots:'robots',
searchfield: ''}
}
render(){
return(
<div className='tc'>
<h1 className=''>RoboFriends</h1>
<SearchBox />
<CardList robots={this.state.robots}/>
</div>
);
}
}
export default App;
I updated the initial code with App.js that calls CardList.
I recently started learning react and I hope to develop an app that lets you search for a user which instantly filters and render the name typed in the search box.
You pass robots as props from App internal state and not from the imported file.
Set the state of App component from the imported robots file
import { robots } from './robots'
class App extends Component {
constructor() {
super()
this.state = {
robots,
searchfield: ''
}
}
render() {
return (
<div className='tc'>
<h1 className=''>RoboFriends</h1>
<SearchBox />
<CardList robots={this.state.robots}/>
</div>
);
}
}
Also using index as React key is a bad practice, You have a unique id in every robot object so use it as key, also read about the map function and how to access the iterated elements
const CardList = ({ robots }) => (
<div>
{robots.map(robot => (
<Card
key={robot.id}
id={robot.id}
name={robot.name}
email={robot.email}
/>
))}
</div>
);
You're passing a string to be mapped, instead pass the robots list of objects and see the result.
These kind of errors are the result of passing something other than a list to be mapped

React-ga not returning correct active page in Google Analytics Dashboard

Context: In the app, I am using react-slick to allows users to navigate through components like a carousel. (NOTE: as users navigate through the carousel, the URL for the application does not change/update; always https: //myApplicationURL.com)
What I am attempting to accomplish: Each component within the carousel uses react-ga to initialize and track pageview analytics on a component level.
What I expect: Google Analytics dashboard will return the correct component name a user is currently viewing.
What is actually happening: Google Analytics dashboard displays an incorrect component name. (Ex: application is on contact component - should display '/contact' but GA dashboard displays another component name)
**CAROUSEL COMPONENT**
import React, { Component } from "react";
import Slider from "react-slick";
import ReactGA from 'react-ga';
import About from '../../components/about';
import {default as Project1} from '../../components/projectTemplate';
import {default as Project2} from '../../components/projectTemplate';
import {default as Project3} from '../../components/projectTemplate';
import {default as Project4} from '../../components/projectTemplate';
import Contact from '../../components/contact';
export default class Carousel extends Component {
constructor(props) {
super(props);
this.state = {
nav1: null,
nav2: null,
pageNumber: 0
};
}
componentDidMount() {
this.setState({
nav1: this.slider1,
nav2: this.slider2
});
}
afterChangeHandler = currentSlide => {
this.setState({
pageNumber: currentSlide++
})
};
render() {
const carousel1 = {
asNavFor: this.state.nav2,
ref: slider => (this.slider1 = slider),
afterChange: this.afterChangeHandler
}
const carousel2 = {
asNavFor: this.state.nav1,
ref: slider => (this.slider2 = slider),
}
return (
<div id="carousel-container">
<Slider {...carousel1}>
<div>
<About props={this.props.props} />
</div>
<div>
<Project1 project={this.props.props.project[0]} />
</div>
<div>
<Project2 project={this.props.props.project[1]} />
</div>
<div>
<Project3 project={this.props.props.project[2]} />
</div>
<div>
<Project4 project={this.props.props.project[3]} />
</div>
<div>
<Contact {/*props*/} />
</div>
</Slider>
<Slider {...carousel2}>
{/*slider2 content*/}
</Slider>
</div>
);
}
}
**ABOUT COMPONENT**
import React from 'react';
import ReactGA from 'react-ga';
const About = props => {
//Google Analytics
ReactGA.initialize('[User ID removed]');
ReactGA.ga('set', 'page', '/about');
ReactGA.ga('send', 'pageview');
return(
<div id="aboutContainer">
{/*Component Content*/}
</div>
);
};
export default About;
**PROJECT COMPONENT**
import React from 'react';
import ReactGA from 'react-ga';
const ProjectTemp = props => {
const name = props.project.name
// Google Analytics
ReactGA.initialize('[User ID removed]');
ReactGA.ga('set', 'page', `/project/${name}`);
ReactGA.ga('send', 'pageview');
return(
<div id="projectTempContainer">
{/*Project Content*/}
</div>
);
};
export default ProjectTemp;
**CONTACT COMPONENT**
import React from 'react';
import ReactGA from 'react-ga';
const Contact = props => {
//Google Analytics
ReactGA.initialize('[User ID removed]');
ReactGA.ga('set', 'page', '/contact');
ReactGA.ga('send', 'pageview');
return(
<div id="contactContainer">
{/*Contact Content*/}
</div>
);
};
export default Contact;
I suggest using the Segment analytics library and following our React quickstart guide to track page calls. If you are rendering individual components inside the carousel, you can use componentDidMount to invoke page calls. You’ll be able to manually set the page name via the parameter, which will help you avoid the issue you’re having with /contact. The example below shows one way you could do this:
export default class CarouselContact extends Component {
componentDidMount() {
window.analytics.page('Contact');
}
render() {
return (
<h1>
Contact page.
</h1>
);
}
}
I’m the maintainer of https://github.com/segmentio/analytics-react. With Segment, you’ll be able to switch different destinations on-and-off by the flip of a switch if you are interested in trying multiple analytics tools (we support over 250+ destinations) without having to write any additional code. 🙂

Reactjs: Axios.post call returns array object from database - need to map to other component

I've been struggling with this for a couple days, and any help would be appreciated.
In this component, I have tried to do an HTTP call to my server and database. After parsing the response, using JSON.parse, I am getting back a correctly formed JSON object. I then want to map through that object and for each return a new component (called HistoryItem).
The code below attempts to do this by placing the object into the component state, but it is causing an infinite refresh loop. Previously I had tried a functional component.
The original iteration of this component did work. But it pulled a static JSON object from my client side files. Therefore, I am confident code works without the http call.
It seems to me I am doing something wrong with the async, which is disallowing the JSON object received asynchronously from being rendered.
Below is the main component. Note the component imports the username from redux. This feeds the HTTP call, so that it retrieves only records associated with the logged in user. Again, everything looks fine on the server/database end...
import React, {Component} from 'react';
import style from './history.css';
import HistoryItem from './HistoryItem/historyItem';
import data from '../../config/fakermyhistory.json';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import axios from 'axios';
class History extends Component {
constructor(props) {
super(props);
this.state = {
compiledList:[]
}
}
getData(){
this.state.compiledList.map((call, i) => {
const shaded = (call.rated) ? 'lightgrey' : 'white';
console.log("shaded", shaded);
return(
<Link to={`/reviewpage/${call._id}`} key={call._id}
style={{ textDecoration: 'none', color:'lightgrey'}}>
<div style={{backgroundColor:shaded}}>
<hr/>
<HistoryItem call={call}/>
</div>
</Link>
)
})
}
render(){
axios.post('/api/history', {username: this.props.username})
.then((res) => {
const array = JSON.parse(res.request.response);
this.setState({compiledList: array})
console.log("res", array);}
).catch((err) => console.log("err", err));
return (
<div className={style.container}>
<div className={style.historyHeader}>
<div className={style.historyHeaderText}>
Your Call History
</div>
</div>
<div className={style.historyList}>
{this.getData()};
</div>
</div>
)
}
}
const mapStateToProps = state => {
return {
username:state.auth.username
};
}
export default connect(mapStateToProps, null)(History);
Thanks in advance if you can help.
Here is another version using it as a functional component. Also doesn't render (although no errors on this one)
import React, {Component} from 'react';
import style from './history.css';
import HistoryItem from './HistoryItem/historyItem';
import data from '../../config/fakermyhistory.json';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import axios from 'axios';
const History =(props)=> {
const getData=(props)=>{
console.log("props", props);
axios.post('/api/history', {username: props.username})
.then((res) => {
const array = JSON.parse(res.request.response);
console.log("array", array);
array.map((call, i) => {
const shaded = (call.rated) ? 'lightgrey' : 'white';
console.log("shaded", shaded);
return(
<Link to={`/reviewpage/${call._id}`} key={call._id}
style={{ textDecoration: 'none', color:'lightgrey'}}>
<div style={{backgroundColor:shaded}}>
<hr/>
<HistoryItem call={call}/>
</div>
</Link>
)
})
}
).catch((err) => console.log("err", err));
}
return (
<div className={style.container}>
<div className={style.historyHeader}>
<div className={style.historyHeaderText}>
Your Call History
</div>
</div>
<div className={style.historyList}>
{getData(props)};
</div>
</div>
)
}
const mapStateToProps = state => {
return {
username:state.auth.username
};
}
export default connect(mapStateToProps, null)(History);
Instead of calling axios in render function, try to invoke it from componentDidMount.
This will help you prevent the infinite loop.
To return the components rendered within the map function, it was necessary to add a "return" command before the map function was called:
return array.map((call, i) => {...

Resources