I'm new to React - native development. I have this json data need to show in render() using {this.state.data.min.en}
{
"status": true,
"message": "good",
"data": {
"min": {
"sin": "text",
"en": " text",
"ta": "text",
"ownere": " text"
}
}
}
The code:
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
AppRegistry,
Alert
} from "react-native";
import { Card } from "react-native-elements";
export default class Home extends Component {
constructor() {
super();
this.state = {
data: []
};
}
handlePress = async () => {
fetch("http://xxx.xx.xx.xx/index.php/testCV/home", {
method: "POST",
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
this.setState({ data: responseJson.data });
})
.catch(error => {
console.error(error);
});
};
componentDidMount() {
this.handlePress();
}
render() {
return (
<View>
<Card>{this.state.data.min.en}</Card>
</View>
);
}
}
AppRegistry.registerComponent("Home", () => Home);
I try it using above code but when i run it i get this error. I try to find way to fix it but no luck.
It's very grateful someone can help me out with this error.
Thanks
You are defaulting your data to an empty array, so when you write this.state.data.min you will get undefined, and then trying to access en on that will give rise to your error.
You could e.g. default the data to null, and wait until your data has been loaded before rendering it.
Example
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
// ...
render() {
const { data } = this.state;
if (data === null) {
return null;
}
return (
<View>
<Card>{data.min.en}</Card>
</View>
);
}
}
Related
I have a fairly simple ASP.NET site with a react front-end. It has a component MetaWeatherForecast that fetches some data from an API endpoint and displays it in a table. That works fine.
After pulling in react-pull-to-refresh into the project and attaching it to the component, the table initially loads and fetches the data on the first load, but then fails as soon as I pull the table to refresh.
Here's a trimmed version of the component in its current form:
MetaWeatherForecast.js
import React, { Component } from 'react';
import authService from './api-authorization/AuthorizeService'
import Moment from 'moment';
import ReactPullToRefresh from 'react-pull-to-refresh'
export class MetaWeatherForecast extends Component {
static displayName = MetaWeatherForecast.name;
constructor(props) {
super(props);
this.state = {
locationForecast: {}, loading: true, success: true, errorMessage: null };
}
componentDidMount() {
this.populateWeatherData();
}
static renderForecastsTable(locationForecast) {
// html markup for the table
}
static renderError(errorMessage) {
// error markup
}
handleRefresh(resolve, reject) {
let success = this.populateWeatherData();
if (success)
resolve();
else
reject();
}
async populateWeatherData() {
this.setState({ locationForecast: {}, loading: true, success: true, errorMessage: null});
const token = await authService.getAccessToken();
const response = await fetch('api/metaweatherforecast/GetFiveDayForecast/44544', {
headers: !token ? {} : { 'Authorization': `Bearer ${token}` }
});
const baseResponse = await response.json();
console.log(baseResponse);
this.setState({ locationForecast: baseResponse.data, loading: false, success: baseResponse.success, errorMessage: baseResponse.errorMessage });
return baseResponse.success;
}
getContent() {
let contents;
if (this.state.loading) {
contents = <p><em>Fetching forecast...</em></p>
} else {
contents = this.state.success
? MetaWeatherForecast.renderForecastsTable(this.state.locationForecast)
: MetaWeatherForecast.renderError(this.state.errorMessage);
}
return contents;
}
render() {
return (
<ReactPullToRefresh
onRefresh={this.handleRefresh}
style={{
textAlign: 'center'
}}>
<div>
<p><em>Pull down to refresh</em></p>
<h1 id="tabelLabel" >Meta Weather forecast</h1>
{this.getContent()}
</div>
</ReactPullToRefresh>
);
}
};
The error being thrown after pulling the table is as follows and is thrown inside the handleRefresh() method:
Uncaught (in promise) TypeError: this.populateWeatherData is not a function
Any ideas or suggestions would be most welcome
In react classes, you have to bind this in the constructor
constructor(props) {
...
this.<method> = this.<method>.bind(this);
}
I like using this library.
Since i am new on React JS,i tried to use map function but it gives me the following error:Uncaught TypeError: totalData.map is not a function.It seems everything is ok in the code,please provide me some feedback.Following below is my codes:
import React, { Component } from 'react';
import axios from 'axios';
export default class TotalData extends Component {
constructor() {
super();
this.state = {
totalData: [],
isfinalData: false
}
}
componentDidMount() {
axios.get('https://nepalcorona.info/api/v1/data/nepal')
.then(res => {
this.setState({
totalData: res.data,
isfinalData: true
})
})
}
render() {
console.log("final data>>", this.state);
const { totalData, isfinalData } = this.state;
let finalData = isfinalData
? totalData.map((item, deaths) => (
<div>
<p>{item.deaths}</p>
</div>
))
: <p>Isloading</p>
return (
<div>
{finalData}
</div>
)
}
}
what may be the issue on my code ?
Following below are my fetched data from API and error i got:
import React, { Component } from 'react'
import axios from 'axios'
export default class App extends Component {
constructor() {
super()
this.state = {
totalData: [],
isfinalData: false
}
}
componentDidMount() {
axios.get('https://nepalcorona.info/api/v1/data/nepal').then((res) => {
this.setState({
totalData: res.data,
isfinalData: true
})
})
}
render() {
console.log('final data>>', this.state)
const { totalData, isfinalData } = this.state
let finalData = isfinalData ? (
<div>
<p>{totalData.deaths}</p>
</div>
) : (
<p>Isloading</p>
)
return <div>{finalData}</div>
}
}
you don't need to use map because you have only one object
After get the comments array from post component and pass it to comments component
the logs start to show the error in the screenshot below
the components are:
import React, { Component } from "react";
import axios from "axios";
import Comments from "../components/comments";
class Article extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
error: "",
comment: ""
};
}
componentDidMount() {
this.getComments();
}
getComments = () => {
const {
match: { params }
} = this.props;
return axios
.get(`/articles/${params.id}/comments`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => {
return response.json();
})
.then(response => this.setState({ comments: response.comments }))
.catch(error =>
this.setState({
error
})
);
};
render() {
return (
<div>
{this.state.title}
<div>
<h2>Comments</h2>
<Comments
getComments={this.getComments}
/>
</div>
</div>
);
}
}
export default Article;
and Comments component
import React, { Component } from "react";
import PropTypes from "prop-types";
import Comment from "./comment";
import axios from "axios";
import Article from "../screens/article";
class Comments extends Component {
constructor(props) {
super(props);
this.state = {
comments: [],
comment: "",
error: ""
};
this.load = this.load.bind(this);
this.comment = this.comment.bind(this);
}
componentDidMount() {
this.load();
}
load() {
return this.props.getComments().then(comments => {
this.setState({ comments });
return comments;
});
}
comment() {
return this.props.submitComment().then(comment => {
this.setState({ comment }).then(this.load);
});
}
render() {
const { comments } = this.state;
return (
<div>
{comments.map(comment => (
<Comment key={comment.id} commment={comment} />
))}
</div>
);
}
}
export default Comments;
so, I've tried to pass it by props, and set the state on comments component.
and instead of use just comments.map I've tried to use this.state but show the same error in the logs.
So, someone please would like to clarify this kind of issue?
seems pretty usual issue when working with react.
If an error occurs you do:
.catch(error => this.setState({ error }) );
which makes the chained promise resolve to undefined and that is used as comments in the Comments state. So you have to return an array from the catch:
.catch(error => {
this.setState({ error });
return [];
});
Additionally it woupd make sense to not render the Comments child at all if the parents state contains an error.
The other way is checking whether it’s an array and if so check it’s length and then do .map. You have initialized comments to empty array so we don’t need to check whether it’s an array but to be on safer side if api response receives an object then it will set object to comments so in that case comments.length won’t work so it’s good to check whether it’s an array or not.
Below change would work
<div>
{Array.isArray(comments) && comments.length>0 && comments.map(comment => (
<Comment key={comment.id} commment={comment} />
))}
</div>
The first time the comments component renders there was no response yet so comments were undefined.
import React, { Component } from "react";
import PropTypes from "prop-types";
import Comment from "./comment";
import axios from "axios";
import Article from "../screens/article";
class Comments extends Component {
constructor(props) {
super(props);
this.state = {
comments: [],
comment: "",
error: ""
};
this.load = this.load.bind(this);
this.comment = this.comment.bind(this);
}
componentDidMount() {
this.load();
}
load() {
return this.props.getComments().then(comments => {
this.setState({ comments });
return comments;
});
}
comment() {
return this.props.submitComment().then(comment => {
this.setState({ comment }).then(this.load);
});
}
render() {
const { comments } = this.state;
if (!comments) return <p>No comments Available</p>;
return (
<div>
{comments.map(comment => (
<Comment key={comment.id} commment={comment} />
))}
</div>
);
}
}
export default Comments;
I want to fetch data from server & show it inside tables. When I directly put code inside the render it works. But, When I encapsulate inside the addElementsToDisplay function & call that function inside render method it doesn't work. Actually, the function gets called, but response is not rendered in table format. Below is my code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Button } from 'semantic-ui-react';
import ResponseRenderer from './responseRenderer';
import "./App.css";
const responseDataContext = React.createContext({});
class App extends Component {
constructor(props) {
super(props);
this.getPastJobs = this.getPastJobs.bind(this);
this.addElementsToDisplay = this.addElementsToDisplay.bind(this);
this.state = { pastJobs: [] }
}
render() {
return (
<div className="App">
<Button onClick={this.getPastJobs}>Get Past Jobs</Button>
<h1> Hello, World! </h1>
{this.addElementsToDisplay()}
</div>
);
}
addElementsToDisplay() {
console.log("state: ", JSON.stringify(this.state));
this.state.pastJobs.map((value, index) => {
return <ResponseRenderer key={Math.random()} data={value} />
});
}
getPastJobs() {
fetch('http://localhost:9090/getPastJobs', {
method: 'POST',
body: JSON.stringify({})
})
.then((response) => {
if (response.status !== 200) {
return;
}
response.json().then((jobs) => {
console.log(jobs);
this.setState({ pastJobs: jobs.data })
});
})
.catch((err) => {
console.log(err.message, err.stack);
});
}
}
export default App;
You are not returning the response and hence it is not rendered, just return the mapped response and it will work fine
addElementsToDisplay() {
console.log("state: ", JSON.stringify(this.state));
return this.state.pastJobs.map((value, index) => {
return <ResponseRenderer key={Math.random()} data={value} />
});
}
Could someone provide me with a little bit of guidance on my class object and how to reference it in another in my project?
Here is my RequestAPI object - request-api.js (note: I understand that there isn't much going on in it yet, but I wanted to walk before I can run)
export class RequestApi {
constructor() {
this.apiBase = '../api';
}
fetch(url, options) {
var options = options || {};
return fetch(this.apiBase + url, options)
.then(_handleResponse, _handleNetworkError);
}
_handleResponse(response) {
if (response.ok) {
return response.json();
} else {
return response.json().then(function (error) {
throw error;
});
}
}
_handleNetworkError(error) {
throw {
msg: error.message
};
}
}
Here is the React Class component that i am trying to reference it in:
import React from 'react';
import { RequestApi } from '../../../../utils/request-api.js';
class UserLayout extends React.Component {
constructor() {
super();
this.state = {
users: [],
isLoading: true
};
this.addNewUser = this.addNewUser.bind(this);
this.editUser = this.editUser.bind(this);
this.deleteUser = this.deleteUser.bind(this);
}
componentDidMount() {
return RequestApi.fetch('/user')
.then(json => {
this.setState({
isLoading: false,
users: json
});
})
.catch(error => {
console.error(error.msg);
});
}
// more code here...
}
I get an error in my React Component Class object: Uncaught TypeError: _requestApi.RequestApi.fetch is not a function
Can anyone provide me with some insight/assistance?
Since fetch is not a static method, you need to create an instance of RequestApi prior to calling fetch on it:
componentDidMount() {
const api = new RequestApi();
return api.fetch('/user')
.then(json => {
this.setState({
isLoading: false,
users: json
});
})
.catch(error => {
console.error(error.msg);
});
}