I have a problem getting state data in the render function.
It works fine and returns the array when I use
console.log(items)
But trying to get first item from the array yields an error
console.log(items[0])
Full code is:
import React from "react";
import StatsSection from "./../components/StatsSection";
import { db } from "./../util/database";
class IndexPage extends React.Component {
constructor(props) {
console.log(props)
super(props);
this.state = {};
}
componentDidMount() {
var data = []
db.collection('test')
.get().then(snapshot => {
snapshot.forEach(doc => {
data.push(doc.data())
})
})
this.setState({
items: data
});
}
render() {
const { items } = this.state
console.log(items[0])
return (
<StatsSection
color="white"
size="medium"
backgroundImage=""
backgroundImageOpacity={1}
items={[
{
title: "Following",
stat: "123"
},
{
title: "Followers",
stat: "456k"
},
{
title: "Likes",
stat: "789"
}
]}
/>
);
}
}
export default IndexPage;
Where am I making the mistake?
You're only setting one item, so items is actually just one item and items[0] fails.
this.setState({
items: data
});
should be inside the .then() so that it only runs after all the items are populated with the .forEach().
Update your componentDidMount() like so:
componentDidMount() {
db.collection('test').get().then(snapshot => {
var data = []
snapshot.forEach(doc => {
data.push(doc.data())
})
this.setState({ items: data })
})
}
Related
Working on a simple project using react js.
What I'm trying to do is to save the "item"(which has an input field for the user to put it) in the localStorage, for the purpose when a user reloads or navigate to other components the item won't be gone, but it will be there.
AddItem.js:
export default class AddItem extends React.Component {
userItems;
constructor(props) {
super(props);
this.state = {
content: "",
items: [],
};
}
update(event) {
this.setState({
message: event.target.value,
});
}
componentDidMount() {
this.userItems = JSON.parse(localStorage.getItem('items'));
if (localStorage.getItem('items')){
this.setState({
items: this.userItems.items,
message: this.userItems.message
})
}else {
this.setState({
items: [],
message: ""
})
}
}
componentWillUpdate(nextProps, nextState){
localStorage.setItem('item', JSON.stringify(nextState));
}
handleClick() {
var items = this.state.items;
items.push(this.state.message);
this.setState({
items: items,
content: "",
});
}
handleChanged(j, event) {
let items = this.state.items;
items[j] = event.target.value;
this.setState({
items: items,
});
}
The problem is that when I type an item in the input field, and I reload the page, the component is not shown at all.
In the application, at the local storage, the value is shown at the google inspect:
But as soon as I navigate to another component or I reload that page, the storage becomes empty like it was in the first time.
How can I make it work, so the value doesn't go away when I navigate to another page?
Remove the logic inside componentWillUpdate and move it to handleItemChanged. Like so:
export default class AddItem extends React.Component {
userItems;
constructor(props) {
super(props);
this.state = {
content: "",
items: [],
};
}
updateMessage(event) {
this.setState({
message: event.target.value,
});
}
handleClick() {
var items = this.state.items;
items.push(this.state.message);
this.setState({
items: items,
content: "",
});
}
handleItemChanged(i, event) {
var items = this.state.items;
items[i] = event.target.value;
this.setState({
items: items,
});
localStorage.setItem('items', JSON.stringify({items, message :""}));
}
componentDidMount() {
this.userItems = JSON.parse(localStorage.getItem('items'));
if (localStorage.getItem('items')){
this.setState({
items: this.userItems.items,
message: this.userItems.message
})
}else {
this.setState({
items: [],
message: ""
})
}
}
renderRows() {
var context = this;
return this.state.items.map(function (o, i) {
return (
<tr key={"item-" + i}>
<td className="2">
<div>
<input
type="text"
value={o}
onChange={context.handleItemChanged.bind(context, i)}
</tr>
I'm trying to pass value from one component to another. First one looks like this:
class ListStation extends Component {
constructor(props) {
super(props)
this.state = {
stations: []
}
this.editStation = this.editStation.bind(this);
}
editStation(id) {
this.props.history.push(`/add-station/${id}`);
}
componentDidMount() {
StationService.getStations().then((res) => {
this.setState({ stations: res.data });
})
}
}
render() {
return (
<div>
<tbody>
{this.state.stations.map(
station =>
<tr key={station.id}>
<td>{station.city}</td>
<td>{station.name}</td>
<td>
<button onClick={() => this.editStation(station.id)} className="btn btn-info">Modify</button>
...
</div>
</div>
);
}
}
export default ListStation;
And another looks like this:
import React, { Component } from 'react';
import StationService from '../services/StationService';
class CreateStationComponent extends Component {
constructor(props) {
super(props)
this.state = {
station: {
id: this.props.match.params.id,
city: '',
name: '',
trains: [
{
number: '',
numberOfCarriages: ''
}
]
}
}
this.changeCityHandles = this.changeCityHandles.bind(this);
this.changeNameHandles = this.changeNameHandles.bind(this);
this.saveStation = this.saveStation.bind(this);
}
componentDidMount() {
if (this.state.station[0].id === '_add') {
return;
} else {
StationService.getStationById(this.state.id).then((res) => {
let station = res.data;
this.setState({ name: station[0].name, city: station[0].city })
});
}
console.log(this.state.station.city + 'dfddddd');
}
But when I try to pass value from one component to another I get error: Property of undefined. The response I get from API looks like this:
I'm trying to edit values based on the id taken from the first component but it seems to fail.
if (this.state.station[0].id === '_add') {
return;
}
Have a look at this if statement from your codebase I think you should remove [0] after this.state.station ... this is because station is an object not an Array
Change it to if (this.state.station.id === '_add') {
My react component won't load the data from the state, at all.
My loading function works as expected, as well as the rendering for it, however, even though the state updates (I logged it, it does return the expected data) nothing with render related to it.
If posts are empty, the <p>nothing</> tag does not show, and if there is data, it's not printed in the p tag nor is it loaded into my carousel.
import React, { Component } from 'react';
import { withFirebase } from '../Firebase';
import AliceCarousel from 'react-alice-carousel';
import 'react-alice-carousel/lib/alice-carousel.css';
import PostItem from '../Market/PostItem';
class LandingPosts extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
loading: false,
posts: [],
limit: 5,
};
}
componentDidMount() {
this.onListenForMessages();
}
onListenForMessages = () => {
this.setState({ loading: true });
this.props.firebase
.collectionGroup('settings')
.where('homepagepost', '==', true)
.get().then(snapshot => {
let posts = [];
snapshot.forEach(doc => {
doc.ref.parent.parent.get().then(doc => {
posts.push({ ...doc.data(), uid: doc.id });
console.log(posts);
});
});
this.setState({ posts: posts.reverse(), loading: false });
});
};
responsive = {
0: { items: 1 },
1024: { items: 3 },
};
render() {
const { loading } = this.state;
return (
<div>
{loading && <div>Loading ...</div>}
{this.state.posts && (
<p>{this.state.posts[0]}</p>
)}
{!this.state.posts && (
<p>nothing</p>
)}
<AliceCarousel
items={this.state.posts.map(item => {return <PostItem data={item}/>})}
responsive={this.responsive}
autoPlayInterval={2000}
autoPlayDirection="rtl"
autoPlay={true}
fadeOutAnimation={true}
mouseDragEnabled={true}
disableAutoPlayOnAction={true}
buttonsDisabled={true}
/>
</div>
);
}
}
export default withFirebase(LandingPosts);
I think, following code is async in in your case.
doc.ref.parent.parent.get().then(doc => {
posts.push({ ...doc.data(), uid: doc.id });
console.log(posts);
});
If so try adding setting state in then or create array of promise like this.
posts.push(
doc.ref.parent.parent.get().then(doc => {
posts.push({ ...doc.data(), uid: doc.id });
console.log(posts);
});
)
Promise.all(posts).then((_posts)=>this.setState({ posts: _posts.reverse(), loading: false });)
I think you have to "repeat" your state declaration inside render.
Like this:
const {
text,
loading,
posts,
limit
} = this.state
At least that's how I have it in my components
In the async function below, I call stationData just to confirm that I'm passing an array of objects into bartData (which is just an empty array). Attached is a response of the array of Objects that I am receiving. However, when trying to use this.state.bartData (to confirm that it does have the array of objects), my return function is returning bartData as undefined. Any ideas?
import React from 'react';
const bartKey = process.env.REACT_API_BART_API_KEY;
class StationBaseRoutes extends React.Component{
constructor(props){
super(props);
this.state = {
isLoading: true,
station: [],
stationAbbv: 'ALL',
destination: '',
bartData: []
}
}
componentDidMount(){
this.getAllStationRoutes();
}
async getAllStationRoutes(){
try{
setInterval(async () => {
const response = await fetch(`http://api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.stationAbbv}&key=${bartKey}&json=y`);
const jsonResponse = await response.json();
const apiData = jsonResponse.root;
const stationData = apiData.station;
console.log(stationData);
this.setState(({
isLoading: false,
bartData: stationData
}), () => {
console.log(`Callback: ${this.state.bartData}`)
})
}, 20000)
} catch(error){
console.log(error);
}
}
getRoutes = () => {
console.log(`bartData: ${this.bartData}`)
}
render(){
const {station, destination} = this.state;
return(
<div>
<h2>Calling get routes: {this.getRoutes()}</h2>
<h2>Origin: {station}</h2>
<h3>Destination: {destination}</h3>
</div>
)
}
}
export default StationBaseRoutes;
Responses: https://imgur.com/gallery/Luk9MCX
There's a couple of bugs here.
First of all, getRoutes() is using this.bartData instead of this.state.bartData
Secondly, all your objects in console.log are being converted to strings. You can change it to
console.log('bartData:', this.state.bartData);
to be able to see the actual data.
I was unable to get the Bart API to work in a codesandbox, so I had to mock the API... however, the data is still structured the same.
On that note, the API is working as expected, you just need to map over the objects in the this.state.bartData array and deconstruct the properties you want to show.
Working example: https://codesandbox.io/s/031pn7w680
import map from "lodash/map";
import React, { Component, Fragment } from "react";
import { fakeAPI } from "../../api/fakeAPI";
class StationBaseRoutes extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
station: [],
stationAbbv: "ALL",
destination: "",
bartData: []
};
this.getAllStationRoutes = this.getAllStationRoutes.bind(this);
}
componentDidMount() {
this.getAllStationRoutes();
}
async getAllStationRoutes() {
try {
const res = await fakeAPI.get();
const apiData = res.data.root;
const stationData = apiData.station;
this.setState({
isLoading: false,
bartData: stationData
});
} catch (error) {
console.log(error);
}
}
render() {
const { bartData, isLoading } = this.state;
return (
<div className="app-container">
{isLoading ? (
<p className="t-a-c">Loading...</p>
) : (
<Fragment>
<h1 className="t-a-c">Bart Stations</h1>
{map(bartData, ({ name, etd }) => (
<div className="jumbotron station" key={name}>
<h1>Origin: {name}</h1>
{map(etd, ({ destination }) => (
<li key={destination}>Destination: {destination}</li>
))}
</div>
))}
<pre className="preview">
<code>{JSON.stringify(bartData, null, 4)}</code>
</pre>
</Fragment>
)}
</div>
);
}
}
export default StationBaseRoutes;
I'm running into an issue right now trying to render a list using react, where I'm saving my react elements into the state, but the problem I'm getting is that the console outputs this:
Uncaught Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
Here is what the state looks like which causes the error:
export default class UserData extends Component {
constructor() {
super();
this.state = {
resultsItems: {}
}
};
componentDidMount() {
fetch(url)
.then(results => {
return results.json();
}).then(data => {
console.log(data.items);
let items = data.items.map((item) => {
console.log(item.title);
return (
<li>
<h2>item.title</h2>
</li>
)
});
this.setState({resultsItems: items});
console.log("state", this.state.resultsItems);
})
.catch(error => console.log(error))
};
render() {
return (
<div>
<button onClick={() => this.props.updateLoginStatus(false)}>
Logout
</button>
<div>
ID: {this.props.user}
{this.state.resultsItems}
</div>
</div>
)
}
}
By way of demonstrating the sort of thing Hamms is talking about in their comment:
class UserData extends Component {
constructor () {
super()
this.state = {
resultsItems: []
}
}
componentDidMount () {
// Simulate API response
const resultsItems = [
{ title: 'foo' },
{ title: 'bar' },
{ title: 'wombat' }
]
this.setState({ resultsItems })
}
render () {
return (
<div>
{this.state.resultsItems.map(item => <ResultsItem item={item} />)}
</div>
)
}
}
function ResultsItem ({ item }) {
return <li>{item.title}</li>
}
However, Chris' answer is correct as to the cause of the error message: the first render tries to use an empty object and not an array, which fails.
It seems like you are correctly setting an array to your state on componentDidMount, however the initial state in your constructor is an object and not an array!
So change this:
this.state = {
resultsItems: {}
}
to this:
this.state = {
resultsItems: []
}