In react native, How to make function in Component to global? - reactjs

Main javascript soure code like this,
import React from 'react'
import LoadingScreen from './components/LoadingScreen'
import './js/Login'
import './js/XHR'
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
load: false,
}
}
XHRget = async parameter => {
this.setState({ load: true });
await XHR.send(parameter)
.then(result => {
this.setState({ load: false });
console.log(result);
});
}
render() {
return (
<View>
<LoginScreen />
<LoadingScreen load={this.state.load}></LoadingScreen>
</View>
);
}
}
export default App
I create XHRget() in App.js for control the 'LoadingScreen' component.
XHR.js has two functions. 1) create and return XMLHttpRequest funciton called create() and 2) get data from server function called send().
And now, I want call the function XHRget() from login() in Login.js but, I don't know how to call.
How can I call the function XHRget() from another js file?

Create a new file with what ever name you like and put the function inside then export it.
ex.
export const XHRget = async (parent,parameter) =>
{
parent.setState({load: true});
await XHR.send(parameter)
.then(result => {
parent.setState({load: false});
console.log(result);
});
}
Remember to pass in this when calling it

Related

Update state with API Call - React.js

I'm trying to update state in React.js using an API call, as I need to show some of the data to the end user.
The api call works through localhost:5001 and is stored in Firebased functions.
import React, { Component } from 'react'
import './Table.css';
class Table extends Component {
constructor (props)
{
super(props);
this.state = {
stocks: []
};
}
componentDidMount() {
fetch('localhost:5001') // Removed for stackoverflow //
.then((response) => response.json())
.then(stockList => {
this.setState =
({ stocks: stockList });
});
}
render() {
return (
<div className='table'>
<h1 id='title'>Companies</h1>
{this.state.stocks.map(stocks => <h2 key={stocks.symbol}> {stocks.companyName}</h2>)}
</div>
)
}
}
export default Table;
Here is a snippet of the API call:
{"symbol":"AAPL","companyName":"Apple Inc"}
setState is a function, so you should call it, rather that assign values to it:
this.setState({ stocks: stockList });

Axios POST res.data is undefined

I have a function which calls an axios.post, this function returns the obejct to the main react App, which should then save it / show it on the screen.
The return of the "postData" function (in API) looks like this:
return axios.post(url, object).then((res) => res.data);
In the main react app, I have:
async postData (file1, file2, algorithm) {
this.setState({
anomalies: await api.postData(file1, file2, algorithm)
}, () => { console.log(this.state.anomalies); }
)
}
When I console.log the anomalies (as in code), I get undefined.
In addition, I have a div as:
<div> {this.state.anomalies} <div/>
Which shows relevant content, but after the call doesn't show anything.
If I do:
axios.post(url, object).then((res) => console.log(res.data);
I get the correct object printed. So then how can I pass this object in the correct way to the React app?
Thanks!
App.js file
import React from "react";
import API from "./API";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { anomalies: null };
}
post = async () => {
this.setState(
{
anomalies: await API.postData()
},
() => {
console.log(this.state.anomalies);
}
);
};
render() {
return (
<div>
<button onClick={this.post}> click</button>
</div>
);
}
}
API.js file
import axios from 'axios'
function postData () {
return axios.get("https://jsonplaceholder.typicode.com/todos/1").then( res => res.data)
}
export default {
postData
}

componentDidMount not firing in React

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import Post from './components/Post.jsx';
import Feed from './components/Feed.jsx';
class App extends React.Component {
constructor() {
super();
this.state = {
view: 'feed',
collection: ''
}
}
componentDidMount() {
console.log('component did mount')
this.getCollection();
}
async getCollection() {
try {
const response = await fetch('/api/page');
const responseJSON = await response.json();
this.setState({ collection: responseJSON }, () => {
console.log("App Component - getCollection() State Updated", this.state);
});
} catch (error) {
console.log("App Component - getCollection() error", error);
}
}
render() {
return (
<div>
Text
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
Can't get component did mount to function. Trying to make an ajax request to my mongodb and render that on the client side. All I need to do now is make a state change setting the collection to the information I get back. I tried using an Ajax request but that didnt work. Now I'm implementing an async fetch call as per the suggestion of another contributor.
the nonworking ajax request:
As of now, componentDidMount is still not being triggered and the collection property of the state is still an empty string.
I would recommend using the Fetch API for AJAX calls and making use of ES6 Async/Await, since importing an entire library just for Ajax seems a bit overkill.
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
collection: ''
}
this.getCollection = this.getCollection.bind(this)
}
componentDidMount() {
console.log('component did mount')
this.getCollection();
}
async getCollection() {
try {
const response = await fetch('/api/blogs');
const responseJSON = await response.json();
this.setState({ collection: responseJSON }, () => {
console.log("App Component - getCollection() State Updated", this.state);
});
} catch (error) {
console.log("App Component - getCollection() error", error);
}
}
render() {
return (
<div>
<h1>Welcome</h1>
</div>
);
}
}
ReactDOM.render(<App /> , document.getElementById('app'));
I'm not sure what you're doing with your render, but I've left it out. Hopefully, this will shed some light on how best to perform what you want.
To get componentDidMount to fire you need the render function. Because first the component renders and then it calls the function componentDidMount.
I think adding this to your class should solve your problem.
render() {
return null;
}

React: Http request response not displaying in render()

Can someone tell me what is wrong with my code below? I am making an HTTP request to Darksky API using 'superagent' and then trying to display the result in an h2 which isn't working. I tried logging it to console and it works perfectly but if I am trying to display it on the page it doesn't work. Could someone help me out pls, I am new to react and not sure what is going wrong.
import React, { Component } from "react";
import "./Body.css";
import Request from "superagent";
class Body extends Component {
constructor() {
super();
this.getData = this.getData.bind(this);
}
getData() {
var url = this.props.apiUrl;
Request.get(url)
.then(response => {
return(JSON.stringify(response.currently.summary));
})
.catch(error => {});
}
render() {
<div>
<h2>
{this.getData()}
</h2>
</div>
}
}
export default Body;
This is the other file where I am importing Body.js :-
import React, { Component } from "react";
import Body from "./Body";
import "./App.css";
class App extends Component {
render() {
return <Body
apiUrl="https://api.darksky.net/forecast/42a9693aecf45c358afbda0022c5cf65/28.5355,77.3910" />;
}
}
export default App;
You need to set your data in the state of the component, it fire new render:
constructor() {
super();
this.getData = this.getData.bind(this);
this.state = {data: {}}
}
componentDidMount() {
var url = this.props.apiUrl;
Request.get(url)
.then(response => this.setState({data: JSON.stringify(response.currently.summary)}))
.catch(error => {});
}
render(){
console.log("your data", this.state.data);
return <div>test</div>;
}
And work with this data with this.state.data.
I advise you to change getData() function to componentDidMount mehtod.
You should use a life cycle method(componentDidMount) with the use of state. It is recommended to make HTTP calls inside the componentDidMount() method.
constructor() {
super();
this.state = {
result: ''
};
}
componentDidMount(){
var url = this.props.apiUrl;
Request.get(url)
.then(response => {
this.setState({
result: JSON.stringify(response.currently.summary)
});
})
.catch(error => {});
}
render() {
<div>
<h2>
{this.state.result}
</h2>
</div>
}

beginner at react.js - rendering component from state which is updated later

I'm trying to test rendering a list component from an JSON object called with fetch, however I suspect the render is called before the JSON is returned as I get an undefined error. Note the debug alert() gets the value, but the render has already error on undefined. How do I handle this? Is there a way to call the render function after the data has been fetched? OR could how would I get the data to render with '?' and then update when the data arrives? Note my if (!object) doesn;t work when called as an inline wrapper - why not - or more impoartanly how would I achive this? Sorry for the begginer questions - I suspect I meant to be using a data framework to bring data for react to display but I wanted to start learning with less frameworks and get the basics. Many thanks! - code is:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class ItemLister extends React.Component {
constructor(props ) {
super(props);
this.state = { items: [] };
}
componentDidMount() {
let url = "http://localhost:8888";
let iterator = fetch(url, {method: 'GET'});
iterator
.then(response => {
//console.log('sss', response)
return response.json();
})
.then(post => {
//console.log(post)
this.state.items = post;
alert(this.state.items.users[3].firstname);
});
}
output(object){
if (!object){
return '?';
}else{
return object;
}
}
render() {
return(
<div>
<div>Items:</div>
<div>{this.output(this.state.items.users[3].firstname)}</div>
</div>
);
}
}
export default ItemLister;
your render function could be something like this:
render() {
const username = (this.state.items === []) ? placeholder : this.output(this.state.items.users[3].firstname;
return(
<div>
<div>Items:</div>
<div>{username}</div>
</div>
);
}
basically, you render a placeholder component until your data arrives, since your data fetch is async and in componentDidMount, so your render will happen initially before you have data.
although you probably want to rethink how this component is constructed in general, why are you accessing specifically users[3]?
Try this code it will help you
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
class ItemLister extends Component {
constructor(props) {
super(props);
this.state = { items: [], firstname: "" };
}
componentDidMount() {
let url = "http://localhost:8888";
let iterator = fetch(url, { method: "GET" });
iterator
.then(response => {
//console.log('sss', response)
return response.json();
})
.then(post => {
//console.log(post)
this.setState({
items: post,
firstname: this.state.items.users[3].firstname
});
alert(this.state.items.users[3].firstname);
});
}
output(object) {
if (!object) {
return "?";
} else {
return object;
}
}
render() {
return (
<div>
<div>Items:</div>
<div>{this.state.firstname}</div>
</div>
);
}
}
export default ItemLister;

Resources