react-native: Using async/await with setState - json

I have this simple code.
export default class ProductDetail extends Component {
constructor(props) {
super(props);
this.state = { test: null,id:this.props.navigation.state.params.productId };
console.log(1);
}
componentWillMount() {
console.log(2);
this.getProductRequest(this.state.id);
console.log(3);
}
async getProductRequest(id) {
try {
let api_token = await AsyncStorage.getItem('apiToken')
let response = await fetch('...')
let json = await response.json();
this.setState({test: json});
} catch(error) {
//
}
}
render() {
console.log(4);
console.log(this.state.test);
return (
<View><Text>test</Text></View>
);
}
}
Now, I checked it in a debuger:
I expect this result:
1
2
3
4
{data: {…}, status: "success", ...}
But I get this:
1
2
3
4
null
4
{data: {…}, status: "success", ...}
I think it means render() run twice!
how can I handle this error?

I think it means render() run twice!
It does: Once before your async result is available, and then again when it is and you use setState. This is normal and expected.
You can't hold up the first render waiting for an async operation to complete. Your choices are:
Have the component render appropriately when it doesn't have the data yet. Or,
If you don't want to render the component at all until the async operation has completed, move that operation in to the parent component and only render this component when the data is available, passing the data to this component as props.

Just to add to T.J Crowder's answer, one thing I like to do is return an ActivityIndicator if data is not received yet.
import {
View,
Text,
ActivityIndicator
} from 'react-native';
export default class ProductDetail extends Component {
... your code ...
render() {
if (!this.state.test) {
return <ActivityIndicator size='large' color='black' />
}
console.log(4);
console.log(this.state.test);
return (
<View><Text>test</Text></View>
);
}
}

Related

Not able to fetch data from server in my ReactJs site

Getting undefined data type error while fetching data from JSON
I have searched at many places but didn't get the suitable answer
import SavedData from "./SavedData";
export default class Saved extends React.Component {
constructor() {
super();
this.state = {
loading: true,
datas: [],
};
}
async componentDidMount() {
const url = "https://todo-list-site.herokuapp.com/todo-data";
const response = await fetch(url);
const todoData = response.json().then((res) => {
this.setState({ datas: res });
});
}
render() {
console.log(this.state.datas[0].description); //not able to get data
return (
<div>
{/* {this.state.datas.map((items) => (
<SavedData
key={items.countTodo}
title={items.title}
desc={items.desc}
/>
))} */}
</div>
);
}
}
Someone help me so that I can proceed
Just like Dave Newton has pointed out in the comments, the render is triggered before the request completes. This is normal and you just need to handle it properly.
If you see the console logs of this codesandbox, you can see that initially this.state.datas is just an empty array [] - so any attempt to access this.state.datas[0].description will be undefined. Only after the state is updated when the request completes, the logs show the data retrieved - this is because according to the mount lifecycle of a React Component, the render() is called before the componentDidMount() and also the request being async.
This is very common and it is even recommended by the official React docs to make HTTP calls in componentDidMount(). The docs also has provided an example to handle this issue.
import SavedData from "./SavedData";
export default class Saved extends React.Component {
constructor() {
super();
this.state = {
loading: true, // we initially set this to true
datas: [],
};
}
async componentDidMount() {
const url = "https://todo-list-site.herokuapp.com/todo-data";
const response = await fetch(url);
const todoData = response.json().then((res) => {
this.setState({
datas: res,
loading: false // when the request is complete, we set this to false
});
});
}
render() {
if (this.state.loading) {
// during the first render, loading will be true and we
// can return a loading message or a spinner
return (
<div>Loading...</div>
);
}
// when render is called after the state update, loading will be false
// and this.state.datas will have the fetched data
console.log(this.state.datas[0].description);
return (
<div>
{this.state.datas.map((items) => (
<SavedData
key={items.countTodo}
title={items.title}
desc={items.desc}
/>
))}
</div>
);
}
}
Your datas state is initially an empty array until your componentDidMount fires and sets the state. As a result, your console log will then be undefined until the state is set. In order to combat this you must wait for this.state.datas[0] to be true before accessing the first objects description within the array. The following code seems to work as expected
import React from "react";
export default class Saved extends React.Component {
constructor() {
super();
this.state = {
loading: true,
datas: []
};
}
async componentDidMount() {
const url = "https://todo-list-site.herokuapp.com/todo-data";
const response = await fetch(url);
response.json().then((res) => {
this.setState({ datas: res });
});
}
render() {
console.log(this.state.datas[0] && this.state.datas[0].description);
return (
<div>
{this.state.datas.map((items, i) => (
<div key={i}>
<div> title={items.title}</div>
<div> desc={items.description}</div>
</div>
))}
</div>
);
}
}

React and chart.js with json

I'm very new in React and JS. I'm trying to create a graph from JSON, but I can't pass value to graph with MAP function and PUSH, my result is just numbers that I put manually (2, 3, 5 - Line 45)
dataGraf.push(hit.minutos) //Works well
this.state.items.map((hit) => (dataGraf.push(hit.minutos))) //No erros, but no data add
My JSON:
[
{"indice":1,"minutos":569,"programa":"seg"},
{"indice":2,"minutos":421,"programa":"ter"},
{"indice":3,"minutos":258,"programa":"quar"}
]
import React,{Component} from 'react';
import Chart from "chart.js";
import Config from '../components/config.js';
let dataGraf = []
class GraphChart extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
this.state = {
items: [],
error: null
};
}
componentDidMount() {
let url1 = `${Config.FullURL}/progativo`
const ctx = this.ctx;
fetch(url1)
.then(items => items.json())
.then((items) => {
this.setState({ items });
});
this.funDadosGrafico()
new Chart(ctx, {
type: "pie",
data: {
labels: ['blue', 'green','red'],
datasets: [
{
label: "# of Likes",
data: dataGraf
}
]
}
});
} //End of componentDidMount
funDadosGrafico(){
dataGraf.push(2, 5, 3) //Just for test
this.state.items.map((hit) => (
dataGraf.push(hit.minutos)))
}
render() {
return (
<div>
<canvas width='800' height='300' ref={ctx => (this.ctx = ctx)}/>
</div>
)
}
}
export default GraphChart;
try moving the execution this.funDadosGrafico() and Canvas creation to componentDidUpdate.
once you call fetch, fetch wont block the thread, hence this.funDadosGrafico() is executed right aftwards. then blocks are executed only after fetch is resolved.
plus, setState method is also async. it is not going to work as expected even if you remove setState from fetch call like:
this.setState(updateMyState)
this.funDadosGrafico() // not going to work also, setState is async

react native: Not able to parse json params

I created a class to get api.
export default class ProductDetail extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
product : []
}
}
componentDidMount() {
this.getProductRequest();
}
...
then create getProductRequest function:
async getProductRequest() {
let response = await fetch('https: ...
let json = await response.json();
console.log(json);
this.setState({ product : json.data});
}
the console result is:
{id: 225782, title: "test", images: Array(1), price: "1$"}
Now in render i get same result:
render() {
console.log(this.state.product);
return (...
Now I try to read params:
render() {
console.log(this.state.product.title);
return (...
But I get this error:
TypeError: Cannot read property 'title' of underfined
what's the wrong?
Edit: Structure:
export default class ProductDetail extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
product : []
}
}
componentDidMount() {
this.getProductRequest();
}
render() {
console.log(this.state.product.title);
return (
<View> <Text style={styles.name}>title</Text></View>
);
}
async getProductRequest() {
try {
let id = this.props.navigation.state.params.productId;
let response = await
fetch('https://www.example.com/product', {
method : 'POST',
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
id
})
});
let json = await response.json();
//json: {"data":{id: 225782, title: "test", images: Array(1), price: "1$"},"status":"success"}
this.setState({ product : json.data});
} catch(error) {
//console.log(error)
}
}
}
...
Because, componentDidMount() re-render after the first execution of rendering. So, when you are putting console.log(this.state.product.title); in the render before return, it doesn't get the title param first time.
After the re-render, the value will be available. So, if you want to check the output put console.log elsewhere or just remove it
Edit
You can call this.getProductRequest(); in componentWillMount() instead of componentDidMount()
componentWillMount() {
this.getProductRequest();
}
let product = JSON.parse(this.state.product
if(product.title){
console.log(product.title)
}
Let with above code. If you are getting string in your state, it may create an issue. Let me know if its work.
As said react official documentation :
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree)
it does mean that first time your render method is unable to read the title of your product (first time that your render method is invoked, this.state.product is still an empty array). I suggest you to check if your array is empty
render() {
if (this.state.product) {
return (
<Text>Loading...</Text>
} else
return (
<View><Text>{this.state.product.title}</Text></View>
)
}
Don't use componentWillMount() because these methods are considered legacy and you should avoid them in new code.
componentWillMount()
If your render function actually does look like you posted, then this can't work. Try chaning your render function to something like this.
render() {
const { product } = this.state
if (!product || !product.title) {
return null
}
return (
<View><Textstyle={styles.name}>product.title</Text></View>
)
}

How to save a list of json data that i get from an API to a class property using fetch

I'm trying to call a localhost API that i created in my react app class. This API will return a list of json data, i'm trying to save these results in a property
I don't know much about Reacjs. What i have tried so far is to create a method that will call the API and return the data, the i call this method in my class and save the results in a property.
The type of this method is Promise since the results that i'm expectibng are a list of data :
let items: any[];
function getIncidentsFromApiAsync(): Promise<any[]>{
return fetch('http://localhost:3978/calling')
.then((response) => response.json())
}
export class App extends React.Component<{}, IDetailsListCustomColumnsExampleState> {
constructor(props: {}) {
super(props);
getIncidentsFromApiAsync().then(json => items = json);
}
}
I haven't been able to see the results since items is always undefined after calling getIncidentsFromApiAsync() method.
You can handle this in React using State and lifecycle method componentDidMount that gets called when the component is ready:
function getIncidentsFromApiAsync(): Promise<any[]>{
return fetch('http://localhost:3978/calling').then(
(response) => response.json()
);
}
export class App extends React.Component<{}, IDetailsListCustomColumnsExampleState> {
constructor(props: {}) {
super(props);
this.state = {
items: []
};
}
componentDidMount() {
getIncidentsFromApiAsync().then(json => this.setState({ items: json });
}
render() {
if (this.state.items.length) {
const itemsList = this.state.items.map((item) => <li key={item}>{item}</li>);
return (
<div>
<ul>{itemsList}</ul>
</div>
);
}
return <div>List is not available</div>;
}
}

null is not an object evaluating this.state.<name>

The problem might be common but I am asking because I couldn't fix it. I am getting "null is not an object(evaluating 'this.state.albums')" at line 22
And also I am a bit not clear about the type of data that was returned after the call and how to handle it. Please, can someone help me in explaining this? I am in the learning phase. when I am directly alert the response.data I'm getting [object][object] I have to do JSON stringify to see the data. Why should we do this?
import React, { Component } from 'react';
import {Text} from 'react-native';
import axios from 'axios';
export default class AlbumList extends Component{
constructor(props) {
super(props);
state = { albums : []};
}
componentWillMount(){
console.log('in componentWillMount');
//debugger;
//alert("first"+this.state);
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then((response) => {
//console.log(response);
//alert(JSON.stringify(response));
this.setState({albums : response.data});
//alert(JSON.stringify(this.state.albums));
})
.catch((error) => {
alert(error);
});
}
renderAlbums(){
return this.state.albums.map( album => <Text>{album.title}</Text>); //line 22
}
componentDidMount() {
console.log('I was triggered during componentDidMount')
}
render(){
return(
<Text>{this.renderAlbums()}</Text>
//<Text>Hiii</Text>
);
}
}
You're missing this in your constructor.
constructor(props) {
super(props);
this.state = { albums : []};
}
As for the alert, you can't alert an object it has to be a string. So alerting a JSON object is just [object object]. If you use JSON.stringify it converts the object to a string that can be used for the alert. In your console you can log objects fine, and their structure is more readable. I would stick to console.log for debugging.