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
}
}
Related
I have created an endpoint in express that handles get requests. From a react component, I make a get request to said endpoint using axios. I want to store the data in an object in my Component class so that it can be accessed at multiple times (onComponentDidLoad, multiple onClick event handlers, etc). Is there a way to store the data outside of the axios promise, and/or preserve the promise so that I can do multiple .then calls without the promise being fulfilled?
I have tried using setState(), returning the promise, and returning the actual data from the get request.
Here is what I have right now:
constructor {
super();
this.myData = [];
this.getData = this.getData.bind(this);
this.storeData = this.storeData.bind(this);
this.showData = this.showData.bind(this);
}
// Store data
storeData = (data) => {this.myData.push(data)};
// Get data from API
getData() {
axios
.get('/someEndpoint')
.then(response => {
let body = response['data'];
if(body) {
this.storeData(body);
}
})
.catch(function(error) {
console.log(error);
});
}
showData() {
console.log(this.myData.length); // Always results in '0'
}
componentDidMount = () => {
this.getData(); // Get data
this.showData(); // Show Data
}
render() {
return(
<Button onClick={this.showData}> Show Data </Button>
);
}
Edit
I was incorrect in my question, storing the promise and then making multiple .then calls works. I had it formatted wrong when i tried it.
This code won't quite work because you're attempting to show the data without waiting it to be resolved:
componentDidMount = () => {
this.getData();
this.showData();
}
As you hinted toward in your original post, you'll need to extract the data from the Promise and there's no way to do that in a synchronous manner. The first thing you can do is simply store the original Promise and access it when required - Promises can be then()ed multiple times:
class C extends React.Component {
state = {
promise: Promise.reject("not yet ready")
};
showData = async () => {
// You can now re-use this.state.promise.
// The caveat here is that you might potentially wait forever for a promise to resolve.
console.log(await this.state.promise);
}
componentDidMount() {
const t = fetchData();
this.setState({ promise: t });
// Take care not to re-assign here this.state.promise here, as otherwise
// subsequent calls to t.then() will have the return value of showData() (undefined)
// instead of the data you want.
t.then(() => this.showData());
}
render() {
const handleClick = () => {
this.showData();
};
return <button onClick={handleClick}>Click Me</button>;
}
}
Another approach would be to try to keep your component as synchronous as possible by limiting the asyncrony entirely to the fetchData() function, which may make your component a little easier to reason about:
class C extends React.Component {
state = {
status: "pending",
data: undefined
};
async fetchData(abortSignal) {
this.setState({ status: "pending" });
try {
const response = await fetch(..., { signal: abortSignal });
const data = await response.json();
this.setState({ data: data, status: "ok" });
} catch (err) {
this.setState({ error: err, status: "error" });
} finally {
this.setState({ status: "pending" });
}
}
showData() {
// Note how we now do not need to pollute showData() with asyncrony
switch (this.state.status) {
case "pending":
...
case "ok":
console.log(this.state.data);
case "error":
...
}
}
componentDidMount() {
// Using an instance property is analogous to using a ref in React Hooks.
// We don't want this to be state because we don't want the component to update when the abort controller changes.
this.abortCtrl = new AbortController();
this.fetchData(this.abortCtrl.signal);
}
componentDidUnmount() {
this.abortCtrl.abort();
}
render() {
return <button onClick={() => this.showData()}>Click Me</button>
}
}
If you just store the promise locally and access it as a promise it should work fine.
getData() {
// if request has already been made then just return the previous request.
this.data = this.data || axios.get(url)
.then( response => response.data)
.catch(console.log)
return this.data
}
showData() {
this.getData().then(d => console.log('my data is', data));
}
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'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.
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've made an application and want to add more components which will use the same json I fetched in "personlist.js", so I don't want to use fetch() in each one, I want to make a separate component that only does fetch, and call it in the other components followed by the mapping function in each of the components, how can make the fetch only component ?
here is my fetch method:
componentDidMount() {
fetch("data.json")
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
items: result.results
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
and here is a sandbox snippet
https://codesandbox.io/s/1437lxk433?fontsize=14&moduleview=1
I'm not seeing why this would need to be a component, vs. just a function that the other components use.
But if you want it to be a component that other components use, have them pass it the mapping function to use as a prop, and then use that in componentDidMount when you get the items back, and render the mapped items in render.
In a comment you've clarified:
I am trying to fetch the json once, & I'm not sure whats the best way to do it.
In that case, I wouldn't use a component. I'd put the call in a module and have the module expose the promise:
export default const dataPromise = fetch("data.json")
.then(res => {
if (!res.ok) {
throw new Error("HTTP status " + res.status);
}
return res.json();
});
Code using the promise would do so like this:
import dataPromise from "./the-module.js";
// ...
componentDidMount() {
dataPromise.then(
data => {
// ...use the data...
},
error => {
// ...set error state...
}
);
}
The data is fetched once, on module load, and then each component can use it. It's important that the modules treat the data as read-only. (You might want to have the module export a function that makes a defensive copy.)
Not sure if this is the answer you're looking for.
fetchDataFunc.js
export default () => fetch("data.json").then(res => res.json())
Component.js
import fetchDataFunc from './fetchDataFunc.'
class Component {
state = {
// Whatever that state is
}
componentDidMount() {
fetchFunc()
.then(res => setState({
// whatever state you want to set
})
.catch(err => // handle error)
}
}
Component2.js
import fetchDataFunc from './fetchDataFunc.'
class Component2 {
state = {
// Whatever that state is
}
componentDidMount() {
fetchFunc()
.then(res => setState({
// whatever state you want to set
})
.catch(err => // handle error)
}
}
You could also have a HOC that does fetches the data once and share it across different components.