I will want to know, if is possible call or execute a method or function from another component.
I would like to run asynchronously the function that is the tableInformacion.js, which has a request get, but after the call of thepost request is made that I have in address.js.
address.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
import {getSolarDayInformation} from './tableInformation.js';
import '../styles/main.css';
class AddressInput extends Component{
constructor(){
super();
this.state = {
address: "",
api:"http://maps.google.com/maps/api/geocode/json?address=",
direccion: "",
latitud: "",
longitud:""
};
}
render(){
return(
<div>
<form>
<input type="text"
value={this.state.address}
onChange={this.updateAdress.bind(this)}
placeholder="Escriba la direccion"/>
<button onClick={this.getAddressGeo.bind(this)}>Consultar</button>
</form>
<ul className="None-Style">
<li><label>Direccion:</label>{this.state.direccion}</li>
<li><label>Latitud:{this.state.latitud}</label></li>
<li><label>Longitud:{this.state.longitud}</label></li>
</ul>
</div>
)
}
updateAdress(event){
this.setState({
address: event.target.value
});
}
getAddressGeo(e){
e.preventDefault();
const apiUrl = this.state.api + this.state.address;
request.post(apiUrl).then((res) => {
const direccionCompleta = res.body.results[0].formatted_address;
const Latitud = res.body.results[0].geometry.location.lat;
const Longitud = res.body.results[0].geometry.location.lng;
this.setState({
direccion: direccionCompleta,
latitud: Latitud,
longitud: Longitud
})
})
.catch((err) => {
console.log(err.message);
});
getSolarDayInformation();
}
}
export default AddressInput;
tableInformacion.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import request from 'superagent';
class TableConsumeInformation extends Component{
constructor(){
super();
this.state = {
apiSolarInformation: 'https://asdc-arcgis.larc.nasa.gov/cgi-bin/power/v1beta/DataAccess.py?request=',
parameters:'execute&identifier=SinglePoint¶meters=ALLSKY_SFC_SW_DWN&',
startDate:'0101&',
endDate:'1231&',
comunity: 'userCommunity=SSE&tempAverage=DAILY&outputList=JSON,ASCII&',
latitudePlace:'lat=',
longitudePlace:'&lon=',
anonymous:'&user=anonymous'
};
}
render(){
return(
<div>
<h2>Information Energy</h2>
<table></table>
</div>
);
}
getSolarDayInformation(){
apiSolarUrl = 'https://asdc-arcgis.larc.nasa.gov/cgi-bin/power/v1beta/DataAccess.py?request=execute&identifier=SinglePoint¶meters=ALLSKY_SFC_SW_DWN&startDate=20170101&endDate=20171231&userCommunity=SSE&tempAverage=DAILY&outputList=JSON,ASCII&lat=11.373&lon=-72.253&user=anonymous';
request.get(apiSolarUrl).then((req, res) => {
console.log(res.body);
});
}
}
export default TableConsumeInformation;
I assume you are talking about the getSolarDayInformation function in this case.
In your case here, it looks like the easiest thing to do would be to refactor your function into its own file and import it into all the places its needed. There is no reason for it to be a object method as it has no dependency on the object state.
You could create a helper functions file, something like
helper.js
export const getSolarDayInformation = () => {
...
}
Then, import the method in your other file(s)
import {getSolarDayInformation} from 'path/to/your/file';
Related
I am trying to re-render the page based on a button click. I have the function updateCowList which calls setState() in my app component. The handleClick logic is in my newCow component which handles the button and the text input.
The console.logs() that I am seeing are 'fire', but I am not seeing the 'after' console.log(), nor am I seeing any of the logs within my updateCowList function in App.
How can I get my updateCowList function to run? I have tried calling it in all sorts of ways, destructuring props, etc.
Here is my App:
import React from 'react';
import CowList from './CowList.jsx';
import CowListEntry from './CowListEntry.jsx';
import axios from 'axios';
import SearchDB from './searchDB.js';
import NewCow from './NewCow.jsx';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cows: []
}
// this.updateCowList = this.updateCowList.bind(this);
}
componentDidMount() {
SearchDB()
.then((res) => {
this.setState({cows: res.data})
}, (err) => {
console.log(err);
});
}
updateCowList(cow) {
console.log('update cow list is running')
oldCows = [...this.state.cows];
newCows = oldCows.push(cow);
console.log('new cows be4 set state', newCows);
this.setState({cows: newCows});
console.log('new cows after set state', newCows);
}
render() {
return (
<div>
<CowList cows={this.state.cows}/>
<NewCow props={this.updateCowList}/>
</div>
)
}
}
export default App;
here is my NewCow component:
import React from 'react';
import axios from 'axios';
class NewCow extends React.Component {
constructor(props) {
super(props);
this.state = {
entry: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
let split = this.state.entry.split(', ')
console.log(split)
axios.post('http://localhost:3000/api/cows', {
name: split[0],
description: split[1]
})
.then(res => { console.log('fire', res.data);
this.props.updateCowList(res.data);
console.log('after')
})
.catch(err => 'error submitting cow :( mooooo');
}
handleChange (event) {
this.setState({entry: event.target.value})
}
render () {
return (
<div className='newCowForm'>
<input className='form-control' type='text' onChange={this.handleChange} value={this.state.entry} placeholder={'name, description'} />
<button onClick={this.handleClick} className='newCowButton'>Create new cow</button>
</div>
)
}
}
export default NewCow;
<NewCow props={this.updateCowList}/>
should be :
<NewCow updateCowList={this.updateCowList}/>
i'm working on react-redux intermidiate..but i don't know what's going wrong
on this project
hera i have creacted the searchbar for getting car details..and the file is created as 'search.js'...you can see here..
search.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getCars } from '../actions';
import { bindActionCreators } from 'redux';
class Search extends Component{
constructor(props){
super(props);
this.state = {
keyword:''
}
}
searchCars = (event) => {
event.preventDefault();
this.props.getCars(this.state.keyword)
}
handleChange = (event) => {
this.setState({
keyword:event.target.value
})
}
componentDidMount(){
console.log(this.state);
}
render(){
return(
<div className="main_search">
<form onSubmit={this.searchCars}>
<input type="text" value={this.state.keyword} onChange = {this.handleChange} />
</form>
</div>
)
}
}
// mapStateToProps
// mapDispatchToProps
function mapDispatchToProps(dispatch){
return bindActionCreators({getCars}, dispatch)
}
export default connect(null,mapDispatchToProps)(Search);
and i think error comes from here about getCars..which is described below as s 'index.js'...you can see here
index.js
const URL_ROOT = 'http://localhost:3004'
export default function getCars(keywords){
const request = fetch(`${URL_ROOT}/carsIndex?q=${keywords}`,
{method:'GET'})
.then(response => response.json())
return{
type:'SEARCH_CARS',
payload:request
}
}
and the error looks like this..
and error showing in bundle.js file
so try to fix it and help me...
Please change your mapDispatchToProps method as
const mapDispatchToProps = (dispatch)=> (
bindActionCreators(getCars, dispatch)
)
I want to pass data from axiosDidMount function to
<p className='title' id='boldTitle'>{data goes here}</p>
I can console.log data and it is working and in my example it is a string "New York City".
I got to the point when I write some input in Search.js Component and it is passed to Results.js Component by this.props.userQuery. So the response.data[1][1] is updating correctly and live in console.log as I write input but I have problem with passing this data that I'm getting from Wikipedia to final destination.
What is proper way to pass this data in this example?
import React from 'react';
import axios from 'axios';
export default class Results extends React.Component {
axiosDidMount(userQuery) {
//const fruits = [];
const wikiApiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&origin=*&search=';
const wikiApiUrlWithQuery = wikiApiUrl + userQuery;
axios.get(wikiApiUrlWithQuery)
.then(response => {
console.log(response.data[1][1]); //New York City
console.log(typeof(response.data[1][1])); //string
//console.log(response.data[2])
//console.log(response.data[3])
//fruits.push(response.data[1]);
})
.catch(err => {
console.log('Error: =>' + err);
});
//return fruits;
}
render() {
//this.props.userQuery from Search.js
const test = this.axiosDidMount(this.props.userQuery);
return(
<div>
<a className='title' href="" target='_blank'>
<div className='result'>
<p className='boldTitle'>{data goes here}</p>
<p></p>
</div>
</a>
</div>
);
}
}
You should separate your concerns. Make a data receiving component, or a container component that handles data retrieval and conditionally renders the component requiring the data once it's available. Something along the lines of the following:
import React, { Component } from 'react';
import axios from 'axios';
const PresentationComponent = (props) => {
// return mark with data
}
const PlaceHolderComponent = (props) => {
// return placeholder markup
}
export default class DataReceivingWrapper extends Component {
constructor(props) {
super(props);
this.state = {
data: null
}
}
componentDidMount() {
axios.get(...)
.then(data) {
this.setState(Object.assign({}, this.state, { data: data }))
}...
}
render() {
if (this.props.data) {
return <PresentationComponent />;
} else {
return <PlaceHolderComponent />; // or null
}
}
}
hi I am trying to post a form with email and password, but I have an error in the function that sends the data, that function you see in the image
action.js
import axios from 'axios';
export const createUser =(usuariosBody, callback) => {
return function(dispatch){
dispatch({type: 'CREATE_USER_REQUEST'});
axios.post('http://localhost:8080/users', usuariosBody)
.then((response)=>{
dispatch({type: 'CREATE_USER_SUCCESS', payload:response.data})
if (typeof callback === 'function') {
callback(null, response.data);
}
})
}
}
component.jsx
class LoginComponent extends Component{
constructor(props) {
super(props);
}
componentDidMount() {
}
render(){
return(
<section className="form-sign brown lighten-5">
<form onSubmit={this.handleSubmit.bind(this)}>
<input ref="email" placeholder='Email' />
<input type="password" ref="password" />
<Button type='submit' >send</Button>
</form>
</section>
)
}
handleSubmit(event) {
this.preventDefault();
const email = ReactDOM.findDOMNode(this.refs.email).value.trim();
const password = ReactDOM.findDOMNode(this.refs.password).value.trim();
// create a user object
const user = {
email,
password
};
// call the action
this.props.createUser(user, function (err, res) {
if (err) {
console.error(err);
} else {
console.log(res);
}
});
}
}
export default LoginComponent;
container.jsx
import React, {Component} from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {createUser} from '../action/action.js';
import {LoginComponent} from '../component/loginComponent.jsx';
class CreateUserContainer extends Component{
componentDidMount(){
}
render (){
return (<LoginComponent createUser={this.props.createUser} />);
}
}
function mapStateToProps(store) {
return {};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
createUser:CreateUser
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(CreateUserContainer);
thanks for your help
You are importing {CreateUser} and trying to use {createUser} in the container.jsx file.
You need to use mapDispatchToProps instead of matchDispatchToProps and also
use CreateUser in you mapDispatchToProps function since you imported it as CreateUser
class CreateUserContainer extends Component{
constructor(props) {
super(props);
}
componentDidMount(){
}
render (){
return(
<LoginComponent createUser={this.props.createUser} />
)
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
createUser:CreateUser
}, dispatch)
}
Also your class must implement the constructor to inherit the props
One more thing is that your handleSubmit function in LoginComponent is not bound
class LoginComponent extends Component{
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
You can also try and console.log(this.props) in your LoginComponent to see if it receives the createUser function
I'm currently using Flickr api to make a Simple Image Carousel and facing a problem where my state does not get updated or rendered whenever I click the button.
Here is my index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import _ from 'lodash';
import Photo from './components/photo';
const urlArr = [];
const apiKey = "API";
const userId = "ID";
const url = `https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=${apiKey}&user_id=${userId}&format=json&nojsoncallback=1`;
class App extends Component {
constructor(props) {
super(props);
this.state = { urlArr: [] };
axios.get(url)
.then((photoData) => {
_.forEach(photoData.data.photos.photo, (photo) => {
urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
});
this.setState({ urlArr });
});
}
render() {
return (
<div>
<Photo urls={this.state.urlArr}/>
</div>
);
}
};
ReactDOM.render(<App/>, document.querySelector('.container'));
and here is my photo.js
import React, { Component } from 'react';
import NextButton from './nextButton';
import PrevButton from './prevButton';
class Photo extends Component {
constructor(props) {
super(props);
this.state = { idx: 0 };
this.nextImg = this.nextImg.bind(this);
}
nextImg() {
this.setState({ idx: this.state.idx++ });
}
render() {
if (this.props.urls.length === 0) {
return <div>Image Loading...</div>
}
console.log(this.state);
return(
<div>
<PrevButton />
<img src={this.props.urls[this.state.idx]}/>
<NextButton onClick={this.nextImg}/>
</div>
);
}
}
export default Photo;
and my nextButton.js (same as prevButton.js)
import React from 'react';
const NextButton = () =>{
return (
<div>
<button>next</button>
</div>
);
};
export default NextButton;
Since I'm fairly new to React, I'm not quite sure why my this.state.idx is not getting updated when I click on the next button (Seems to me that it is not even firing nextImg function either). If anyone can give me a help or advice, that would really appreciated.
Thanks in advance!!
Update your NextButton. Use the event within your presentational component.
<NextButton next={this.nextImg}/>
And the NextButton component should looks like this.
import React from 'react';
const NextButton = (props) =>{
return (<div>
<button onClick={props.next}>next</button>
</div>
);
};
The problem lies with this piece of code:
axios.get(url)
.then((photoData) => {
_.forEach(photoData.data.photos.photo, (photo) => {
urlArr.push(`https://farm6.staticflickr.com//${photo.server}//${photo.id}_${photo.secret}_z.jpg`);
});
this.setState({ urlArr });
});
this refers to the axios.get callback scope and not the Component. You can define another variable called self or something that makes more sense to you and call self.setState().
See this question for a similar problem: Javascript "this" scope