I'm fetching data from my backend to my frontend. After I invoke
let data = response.json(), I then invoke const bartData = Object.entries(data). So, I'm creating an array that holds the key/value pairs of my original object. I then set the state of my component this.setState({allStations: bartData}), where the property allStations: []. This is where the problem comes up- I want visual confirmation that I'm geting the right data and manipulate it the way I want to so I invoke console.log(this.state.allStations[0]) and it gives me the correct contents but when I go further console.log(this.state.allStations[0][0], I get an error that states
this.state.allStations[0] is undefined
Why?
Also, I get that I'm putting an array inside of an array, which is why I was surprised that console.log(this.state.allStations[0])gave me the contents of the original array. Picture of console.log(this.state.allStations) this.state.allStations
constructor(){
super(props);
this.state = {
allStations: []
}
}
async getAllStations(){
try{
const response = await fetch(`/base-station-routes`);
let data = await response.json();
// console.log(response);
// let test = JSON.parse(bartData);
// console.log(test)
const bartData = Object.entries(data);
// console.log(bartData[0][0]) works
this.setState({
allStations: bartData
})
}catch(e){
console.log(`Error: ${e}`)
}
}
render(){
console.log(this.state.allStations[0]);
return( more stuff )
}
[1]: https://i.stack.imgur.com/hQFeo.png
In render function before console.log(this.state.allStations[0]) you should check the state value.
Render function executes before fetching data from backend, my suggestion to do this
if(this.state.allStations) && console.log(this.state.allStations[0])
Do a conditional render to prevent it from showing the array before response has been sent.
Add something like:
constructor(){
super(props);
this.state = {
isLoading: true,
allStations: []
}
}
You need to use React Lifecycles and stick Fetch inside:
componentWillMount(){
fetch('/base-station-routes') // Already Async
.then(res => res.json()) // Convert response to JSON
.then(res => this.setState({ isLoading: false, allStations: res})) // you can call it bartData, but I like to stick with res
.catch(err => { //.catch() handles errors
console.error(err)
})
}
and then in your Render:
render(){
return(
<div>
{this.state.isLoading ? <span>Still Loading</span> : // do a map here over your data}
</div>
)
}
This prevents doing anything with the data before your response is there.
Related
I am using React-Native and am having issues just getting data to render from an API, into the render function. I'm running node JS and express on one end to pull some data from a SQL database. This returns JSON that looks like this:
{"routines":[{"routine_id":1,"name":"Morning Routine","start_time":"2020-03-09T14:24:38.000Z","end_time":"2020-03-09T15:24:44.000Z","is_approved":0}]}
I want to loop through the routines key and print out each routine as components in React. I don't really care about what type of component that gets used, I just want to get the data. I've tried a few methods:
Method 1: Using componentDidMount with fetch:
constructor() {
super();
this.state = { routines: {} }
}
componentDidMount() {
fetch('http://localhost:3000/routines')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.then( routines => {
this.setState({routines: routines});
})
.catch( error => {
console.error(error);
});
}
render() {
console.log(this.state)
render of this.state logs an empty object, despite the then(routines portion of the code returning the correct data.
Method 2: Putting everything in componentDidMount
async componentDidMount() {
const response = await fetch("http://localhost:3000/routines")
const json = await response.json()
console.log('json');
console.log(json);
const routines = json.routines
this.setState({routines})
}
Again, logging the state in render produces nothing while logging the json that gets returned from componentDidMount does return valid data.
Inside the render method i've also tried:
const { routines } = this.state;
And routines comes up as undefined.
Method 3: Directly calling a function to set the state.
constructor() {
super();
this.state = { routines: this.fetchData() }
}
This ends up returning some weird data:
{"routines": {"_40": 0, "_55": null, "_65": 0, "_72": null}}
I'm assuming it's because react native does not want me to do this.
I just want a simple way to fetch data from an API and display that data in render. I've gone through about four tutorials and all of them end up with undefined or objects set as the default value in the constructor in the render method. Am I going crazy? It feels like this is somehow impossible..?
You do everything right, just use state in render and you will see updates.
constructor() {
super();
this.state = { routines: [] }
}
render() {
const { routines } = this.state
return (
<View>
{routines.map(item => <Text>{item.name}</Text>)}
</View>
)
}
Since fetch is an async task the data this.setState({routines}) get's set after render() is executed. You can execute this.forceUpdate() after setting this.setState({routines}). This will re-execute render() when the data is set.
See: https://reactjs.org/docs/react-component.html#forceupdate
However, debugging mode can also be the culprit.
its may be because fetch call is async ,and your render method may try to use it before its loaded by the api call,
so your componentDidMount should be like
componentDidMount() {
this.setState({routines:null})
//fire an api call
fetch('http://localhost:3000/routines')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.then( routines => {
this.setState({routines: routines});
})
.catch( error => {
console.error(error);
});
}
now inside your render function you should first confirm that routines is not null and have some valid values like
render(){
if(this.state.routines !==null){
//your code to render component
}else{
//your loading or error message
}
}
I'm trying to save in the state of my component the data an Api call retrieves, but the data have no time to come cause of the async function so when I check the state its value is an empty array. Here is the code.
async getValuesData() {
let id = "dataid";
let getValuesCall = urlCallToDatabase + "valuesById/" + id;
const response = await fetch(getValuesCall, { headers: {'Content-Type': 'application/json'}})
const res = await response.json()
this.setState = ({
values: res
})
console.log("Data Values: ", res);
console.log("Data Values from state: ", this.state.values);
}
I'm calling the function in the contructor.
First, you've to call the function inside ComponentDidMount lifecycle if you want the component to appear as soon as the data is mounted
Second,I'd do the following:
I declare, either in the same file or in a different one, for example, x.business.js the function that calls the backend and returns the result:
const getValuesData = async () => {
const id = "dataid";
const getValuesCall = urlCallToDatabase + "valuesById/" + id;
const response = await fetch(getValuesCall, { headers: {'Content-Type': 'application/json'}})
return await response.json();
}
Then in the component, if I want it to be called as soon as it is assembled, this is when I make the assignment to its state (and if you want to check that it has been set, you use the callback that setState has after the assignment):
class SampleComponent extends React.Component {
state = {
values: {}
}
componentDidMount() {
getValuesData().then(response =>
this.setState(prevState => ({
...prevState,
values: response
}), () => {
console.log(this.state.values);
}))
}
...
}
As the community says, it's all in the documentation:
componentDidMount: if you need to load data from a remote endpoint and update your state
setState(): to update state of the component
Here's an example of how it would work
You're calling setState incorrectly. It should be:
this.setState({ values: res });
The console.log() calls, even if you adjust the above, won't show accurately what you expect. If that's what you want try this too:
this.setState({ values, res },
() => {
console.log("Data Values: ", res);
console.log("Data Values from state: ", this.state.values);
}
);
I.e., make the console.log()'s the second argument to setState which will then accurately show the value of state.
You should do this :
this.setState({values: res})
this.setState should be a function : https://reactjs.org/docs/react-component.html#setstate
You have to use setState instead of this.state = {}
this.setState({values: res})
Use like this
this.setState({values: res})
use this.setState() to schedule updates to the component local state
Do Not Modify State Directly
// Wrong
this.state.values = res
Instead, use setState()
// Correct
this.setState({values: res});
I am getting two time data null and data, what is my problem? And, why should I write two time data? Is it problem with json? Can anybody help me?
Contex.js
class ProviderWrapper extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
isLoading: false
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch(URL + JSON_PATH)
.then(response => response.json())
.then(data => this.setState({ data, isLoading: false }));
}
render() {
const { children } = this.props;
return <Context.Provider value={this.state}>{children}</Context.Provider>;
}
}
test.js
import React, { Component } from "react";
import { Ctx } from "../Context/Context";
class Menu extends Component {
static contextType = Ctx;
render() {
const { data } = this.context;
console.log("data",data)
return (
<MenuWrapper>
{data && data.name}
</MenuWrapper>
);
}
}
data in ProviderWrapper starts out null and you don't start the fetch until componentDidMount, so data will be null for at least one call to render. You haven't shown what Menu and ProviderWrapper are both in, but Menu's render will be called whenever it needs to render, regardless of whether the fetch is done. It's not at all surprising that it does that at least once, and twice doesn't seem odd either.
Menu needs to be able to handle it when data is null (which it already seems to, so that's good).
A couple of side notes:
It's not the problem, but you're falling prey to a footgun in the fetch API: You need to check ok before calling json, details on my anemic little blog.
You're not handling errors at all. If the fetch fails for whatever reason, your ProviderWrapper is just left in the loading state forever. You need to handle errors.
Here's what that fetch call should look like:
fetch(URL + JSON_PATH)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
response.json();
})
.then(data => this.setState({ data, isLoading: false }))
.catch(error => {
// ...handle/show error here and clear the loading state...
});
(In my projects, I have a wrapper for fetch so I don't have to do that every time. Making HTTP errors fulfillments rather than rejections was a major mistake in the API.)
I try to create my first hybrid App with ReactNative. I have an issue with my Array.map…
class HomeScreen extends React.Component {
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: {}
};
async getPokemonFromApiAsync() {
try {
this.setState({isLoading: true});
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
return this.setState({
isLoading: false,
data: await response.json()
});
} catch (error) {
console.error(error);
}
(...)
componentWillMount() {
this.getPokemonFromApiAsync()
}
(...)
result = (result = this.state.data.results) => {
console.log('test', this.state.data);
return (
<View>
(...)
result.map( (item, index) => {
(...)
}
</View>
)
}
}
I don't understand, why my function getPokemonFromApiAsync is empty. iOS Simulator returns a TypeError: Undefined is not an object (evaluating 'result.map')
And when adding a constructor like:
constructor(props) {
super(props)
this.getPokemonFromApiAsync = This.getPokemonFromApiAsync.bind(this)
}
I have an many errors in console:
Warning: Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the %s component., setState, HomeScreen
For me, it's normal…
What is a good lifecycle for an asynchronous Http request?
Best way using axios library github link
npm install axios
Finally, weekly downloads are more than 4,000,000+ Github Starts 50,000+
Your error is caused by how you have set up your initial data in state.
You have set it up as:
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: {} // <- here you define it as an object, with no parameters
};
You should be setting it as an object with a results parameter`. So your initial state should look like
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: { results: [] } // <- here you should define the results inside the object
};
The reason you are getting the error:
TypeError: Undefined is not an object (evaluating 'result.map')
Is because on the initial render, before your fetch response has come back, it is trying to map over this.state.data.results which doesn't exist. You need to make sure that there is an initial value for results in the state.
That should stop the initial error, however you will have to make sure that what you are saving into state for data is also an array, otherwise you will continue to get the same error.
componentWillMount has been deprecated and you should be using componentDidMount.
Also as you are calling an async function inside you componentWillMount you should refactor it in the following way:
async componentDidMount() {
await this.getPokemonFromApiAsync()
}
So that the mounting doesn't occur until the fetch request has been completed.
I would also refactor your getPokemonFromApiAsync so that you get the response.json() before trying to set it into state. You also don't need the return statement as this.setState doesn't return anything.
async getPokemonFromApiAsync() {
try {
this.setState({isLoading: true});
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
let data = await response.json(); // get the data
this.setState({
isLoading: false,
data: data // now set it to state
});
} catch (error) {
console.error(error);
}
Snack:
Here is a very simple snack showing the code working https://snack.expo.io/#andypandy/pokemon-fetch
Code for snack:
export default class App extends React.Component {
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: { results: [] } // <- here you should define the results inside the object
};
getPokemonFromApiAsync = async () => {
try {
this.setState({ isLoading: true });
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
let data = await response.json(); // get the data
this.setState({
isLoading: false,
data: data // now set it to state
});
} catch (error) {
console.error(error);
}
}
async componentDidMount () {
await this.getPokemonFromApiAsync();
}
render () {
return (
<View style={styles.container}>
{this.state.data.results.map(item => <Text>{item.name}</Text>)}
</View>
);
}
}
A better way is to implement your state values when your promise is resolved using "then".
let response = fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20')
.then((response) => {
this.setState({
isLoading: false,
data: response.json()
});
});
Maybe you can process your data (result.map) in the Promise callback and directly insert the result in your component.
And by the way, XHR calls are generally processed in the componentDidMount method.
The reason you are getting the error TypeError: Undefined is not an object (evaluating 'result.map') is that you are getting the result from this.state.data.results, but because data is async, at the first time it renders, data is {} (because you set it in the state), so data.result is undefined and you can't use .map() in a undefined.
To solve this, you can check if data.result is not undefined, before render it.
return (
<View>
(...)
result && result.map( (item, index) => {
(...)
}
</View>
)
I am learning react, and I have made a sample tv show app using an example off freecodecamp. It is all working okay from what I can see however after searching for something and then backspacing everything in the search box, it shows results when it shouldn't be, can anyone see a mistake I have made in my code?
class SeriesList extends React.Component {
state = {
series: [],
query: ''
}
onChange = async e => {
this.setState({query: e.target.value});
const response = await fetch(
`https://api.tvmaze.com/search/shows?q=${this.state.query}`
);
const data = await response.json();
this.setState({series: data});
}
render(){
return (
<div>
<input type="text" onChange={this.onChange} value={this.state.query} />
<ul>
<SeriesListItem list={this.state.series} />
</ul>
</div>
);
}
}
I have it on codepen here.
https://codepen.io/crash1989/pen/ERxPGO
thanks
One else point you can use await for setState
onChange = async e => {
await this.setState({query: e.target.value});
const response = await fetch(
`https://api.tvmaze.com/search/shows?q=${this.state.query}`
);
const data = await response.json();
this.setState({series: data});
}
Your request will be performed after changing query
setState works async. So there is no guarantee, that this.state.query has been updated after calling this.setState({query: e.target.value}). So your url contains the previous state eventually.
There are two options:
Use the event data for the new query:
const response = await fetch(
`https://api.tvmaze.com/search/shows?q=${e.target.value}`
);
...
Use the setState callback second arg
this.setState({query: e.target.value}, () => {
const response = await fetch(
`https://api.tvmaze.com/search/shows?q=${this.state.query}`
);
...
})
This is a good article about the async nature of setState https://medium.com/#wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3.
Problem
There are race conditions: When you type two+ letters you make two+ network calls. The first network call may be last to complete, and then you show results for the wrong query.
I fixed it in this pen: https://codepen.io/arnemahl/pen/zaYNxv
Solution
Keep track of results for all queries you have ever gotten the response to. Always how the data returned for the current query. (Also, don't make multiple API calls for the same query, we already know).
state: {
seriesPerQuery: {}, // Now a map with one result for each query you look up
query: [],
}
...
onChange = async e => {
...
// Now keep the results of the old querys, in addition to the new one
// whenever you get an API response
this.setState(state => ({
seriesPerQuery: {
...state.seriesPerQuery,
[query]: data,
}
}));
}