React class component state value not updating - javascript

I am new to react js. I am learning it by creating a simple app. I tried to create a simple weather app using react class component. All working fine but the result stored in a state variable is not printing in the template. I can see the API response in the console and then store the result on the 'currWeatherRes' state variable which is not showing in the template (Location is always blank)
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(){
super();
this.state = {
cityName: "",
currWeatherRes: {}
}
}
handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was:`+ this.state.cityName);
fetch(`https://api.openweathermap.org/data/2.5/weather?q=`+this.state.cityName+`&appid=f3ee66722740d00cc6f197cbcab3d534`, {
method: 'GET'
}).then((response) => {
console.log(response)
this.setState({
currWeatherRes: response
})
//return response.json();
});
}
handleChange = (event) => {
this.setState({cityName:event.target.value});
}
render() {
return (
<div className="weather-app">
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Enter City"/>
<button type="submit" value="Submit">Submit</button>
</form>
{(typeof this.state.currWeatherRes.main != "undefined") ? (
<div className="weather-details">
<div className="weather-location">
<div className="location">Loctaion: {this.state.currWeatherRes.name}</div>
</div>
</div>
):('')}
</div>
);
}
}
export default App;

The problem was not related to react but the way you handled API call.
Fix:
fetch(`https://api.openweathermap.org/data/2.5/weather?q=`+this.state.cityName+`&appid=f3ee66722740d00cc6f197cbcab3d534`, {
method: 'GET'
}).then((response) => {
return response.json();
}).then((res) => {
this.setState({
currWeatherRes: res
})
});
Working code:
import React, { Component } from 'react';
class App extends Component {
constructor(){
super();
this.state = {
cityName: "",
currWeatherRes: {}
}
}
handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was:`+ this.state.cityName);
fetch(`https://api.openweathermap.org/data/2.5/weather?q=`+this.state.cityName+`&appid=f3ee66722740d00cc6f197cbcab3d534`, {
method: 'GET'
}).then((response) => {
return response.json();
}).then((res) => {
this.setState({
currWeatherRes: res
})
});
}
handleChange = (event) => {
this.setState({cityName:event.target.value});
}
render() {
console.log(this.state.currWeatherRes)
return (
<div className="weather-app">
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Enter City"/>
<button type="submit" value="Submit">Submit</button>
</form>
{(typeof this.state.currWeatherRes.main != "undefined") ? (
<div className="weather-details">
<div className="weather-location">
<div className="location">Loctaion: {this.state.currWeatherRes.name}</div>
</div>
</div>
):('')}
</div>
);
}
}
export default App;

Related

How can I pass an object ID from mapped array to backend?

I want to pass the ID of an object to the backend. The objects are mapped from the array and there should be a separate button for each one so that the ID of each individual object can be pass to the backend.
The communication between backend and frontend works. The only problem is that the ID is not sent to the backend when the submit button is clicked. If I would now work with an OnChange and enter the ID myself in the text field, then it would work without any problems.
Does somebody has any idea?
Here my code:
import React from 'react';
import {format} from "date-fns-tz";
import {Link} from "react-router-dom";
import MailQueueDataService from "../services/mail_queue.service";
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
mailqueues_unsent: {},
loading: false
}
this.parentClassFunction = this.parentClassFunction.bind(this);
}
parentClassFunction = () => {
console.log("TEST");
event.preventDefault();
const url = "/api/v1/mail_queues/authorize_mail_queue";
const { id } = this.state;
const body = {
id,
};
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "POST",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.props.history.push(window.close()))
.catch(error => console.log(error.message));
}
render() {
return (
<div>
<Child
parentClassFunction={this.parentClassFunction}
/>
</div>
)
}
}
class Child extends React.Component{
constructor(props){
super(props);
this.state = {
mail_queues_unsent: [],
loading: false
}
}
onClickSubmitButton = () =>{
this.props.parentClassFunction()
};
retrieveMailQueues() {
MailQueueDataService.getAll().then(response => {
if (this._isMounted)
this.setState({
mail_queues_unsent: response.data.mailqueues_unsent,
loading: false}
)
}).catch(e => {
console.log(e)
})
}
componentDidMount() {
this._isMounted = true;
this.setState({loading: true})
this.retrieveMailQueues();
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
if (this.state.loading) {
return <div className="col text-center"> Lade Unautorisierte Mails... </div>;
} else {
const {mail_queues_unsent} = this.state;
const allMailsUnsent = mail_queues_unsent.map((mailqueues_unsent, index) => (
<div className="col">
<div key={index}>
<h4><b>Empfänger:</b>{mailqueues_unsent.company_name}</h4>
<b>Datum Versandfreigabe:</b>
{format(new Date(mailqueues_unsent.created_at), 'dd.MM.yyyy hh:mm')}
<p><b>Anzahl der Tests:</b> {mailqueues_unsent.trials_count}</p>
<b>Tests:</b>
<p>{mailqueues_unsent.trials.map(trial => <Link to={"/trials/" + trial.id}>
<p>{trial.certificate_number}</p></Link>)}</p>
<form onSubmit={this.parentClassFunction}>
<label htmlFor="id"></label>
<input
type="text"
name="id"
id="id"
value={mailqueues_unsent.id}
className="form-control"
onChange={this.onChange}
/>
<button onClick={this.onClickSubmitButton.bind(this)}>CLICK</button>
</form>
</div>
</div>
));
const noMailQueues = (
<div>
<h4>
Kein Unautorisierte Mails vorhanden.
</h4>
</div>
);
return (
<div>
{mail_queues_unsent.length > 0 ? allMailsUnsent : noMailQueues}
</div>
)
}
}
}
export default Parent;
Since you are calling a function that is passed as prop from the parent, inside the child component you should call it on submit like this (its not this but this.props):
onSubmit={this.props.parentClassFunction}

React.js translate component not showing on the browser

I am trying to create a web app in which user search for a word using 'Form' component and then the result is fetched from an API and then passed to 'translate' component, but my 'translate' component is not showing in the browser.
form.jsx
import React from "react";
import "./form.scss";
import Translate from "./translate"
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
term: "",
getdata: []
}
}
handleChange = (e) => {
e.preventDefault();
this.setState({ [e.target.name]: e.target.value });
};
componentDidMount() {
}
submit = (e) => {
e.preventDefault();
const { term } = this.state;
const rawUrl="https://mashape-community-urban-dictionary.p.rapidapi.com/define?term="+term;
const url=rawUrl;
fetch(url, {
"method": "GET",
"headers": {
"x-rapidapi-host": "mashape-community-urban-dictionary.p.rapidapi.com",
"x-rapidapi-key": "c8cb6b8cccmshc02b57f0b5a8c98p1516cdjsnb64d72a5ad33"
}
})
.then(response => {
return response.json();
})
.then(data=>{
this.setState({getdata:[data.list]});
console.log(this.state.getdata);
})
.catch(err => {
console.log(err);
});
}
render() {
const translate=this.state.getdata.map(item => (<Translate word={item.word} definition={item.definition} />))
return (
<div class="full">
{translate}
<div class="searchForm">
<form>
<input type="text" name="term" value={this.state.term} placeholder="Enter a word here" onChange={this.handleChange}></input><button onClick={this.submit}>Search</button>
</form>
</div>
</div>
);
}
}
export default Form;
translate.jsx
import React from "react";
import "./translate.css";
class Translate extends React.Component {
render() {
return (
<div class="all">
<div class="single">
<div class="word">
{this.props.word}
</div>
<div class="def">
{this.props.definition}
</div>
</div>
</div>
);
}
}
export default Translate;
Can anyone solve this error.
I am stuck on this for a long time.
The issue is that you're saving the array returned by the API call within another array this.setState({getdata:[data.list]});. This is making it difficult to parse. Below is a working example which has been simplified due to limited access to your css files:
Form.js
import React from "react";
import Translate from "./Translate";
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
term: "",
getdata: []
};
}
handleChange = (e) => {
e.preventDefault();
this.setState({ [e.target.name]: e.target.value });
};
componentDidMount() {}
submit = (e) => {
e.preventDefault();
const { term } = this.state;
const rawUrl =
"https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=" +
term;
const url = rawUrl;
fetch(url, {
method: "GET",
headers: {
"x-rapidapi-host": "mashape-community-urban-dictionary.p.rapidapi.com",
"x-rapidapi-key": "c8cb6b8cccmshc02b57f0b5a8c98p1516cdjsnb64d72a5ad33"
}
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log("DATA", data.list);
this.setState({ getdata: data.list });
})
.catch((err) => {
console.log(err);
});
};
render() {
const translate = this.state.getdata.map((item) => (
<Translate
word={item.word}
definition={item.definition}
key={item.defid}
/>
));
return (
<div>
<div>
<form>
<input
type="text"
name="term"
value={this.state.term}
placeholder="Enter a word here"
onChange={this.handleChange}
></input>
<button onClick={this.submit}>Search</button>
</form>
{translate}
</div>
</div>
);
}
}
export default Form;
Translate.js
import React from "react";
export default function Translate(props) {
const { word, definition } = props;
return (
<div>
<div>
<div>{word}</div>
<div>{definition}</div>
</div>
</div>
);
}

My React state doesn't stay on my components

In my code, I use a click event on the InterestBox in order to update the appearance of the InterestBox and to change the state of the parent of the parent of InterestBox.
However, when I inspect the element with the React Developer Tools or that I try to send a request to my API, the state.interests is always empty. But, when I log the state in the console, it shows an array with a length of 0, but containing all the proper values.
I tried to find what is wrong with my code, but I think I need an external look to find what is wrong.
import axios from 'axios';
import * as Cookies from 'js-cookie';
import React, { Component } from 'react';
import Button from '../../components/Button';
import Dashboard from '../Dashboard';
import ErrorContainer from '../../components/ErrorContainer';
import InterestList from '../../components/register/InterestList';
export class EditUser extends Component {
constructor(props) {
super(props);
this.state = {loading: true, interests: []}
this.addInterest = this.addInterest.bind(this);
this.logState = this.logState.bind(this);
}
addInterest(id, name) {
console.log('hoppity hippity you parenty')
var mid = 'm' + id;
console.log(this.state.interests[mid] == undefined)
if(this.state.interests[mid] == undefined) {
console.log(this.state);
this.setState((state) => {
state.interests[mid] = name;
return {interests: state.interests}
}, () => {
console.log(JSON.stringify(this.state.interests))
})
} else {
console.log('deleted')
var newInterest = this.state.interests;
delete newInterest[mid]
this.setState({interests: newInterest})
}
console.log(this.state.interests)
}
componentDidMount() {
var token = Cookies.get('token');
axios.get('http://localhost:8000/api/details', {headers: {"Accept": 'application/json', "Authorization": `Bearer ${token}`}}).then(
(success) => {
this.setState({
loading: false,
firstname : success.data.data.user.firstname,
lastname: success.data.data.user.lastname,
email: success.data.data.user.email,
dob: success.data.data.user.dob,
address: success.data.data.user.address,
uinterests: success.data.data.interests
})
}, (error) => {
this.props.history.push('/deconnexion');
}
)
var places = require('places.js');
var placesAutocomplete = places({
appId: "plZJLSHIW8M5",
apiKey: "0eddd2fc93b5429f5012ee49bcf8807a",
container: document.querySelector('#address-input')
});
}
logState() {
console.log(this.state);
}
render() {
return (
<Dashboard loading={this.state.loading}>
<h1 className="title">Modifier mon profil</h1>
<form className="user-form offer-update-form" onSubmit={this.handleSubmit}>
<label>Prénom :</label>
<input type="text" name="firstname" value={this.state.firstname} onChange={this.handleChange}></input> <br />
<label>Nom de famille :</label>
<input type="text" name="lastname" value={this.state.lastname} onChange={this.handleChange}></input> <br />
<label>Email :</label>
<input type="email" name="email" value={this.state.email} onChange={this.handleChange} /><br />
<label>Adresse :</label>
<input type="address" id="address-input" name="address" value={this.state.address} onChange={this.handleChange} /><br />
<label>Date de naissance :</label>
<input type="date" name="dob" value={this.state.dob} onChange={this.handleChange} /><br />
<InterestList alreadyChecked={this.state.uinterests} onClick={this.addInterest} />
<ErrorContainer errors={this.state.errors} />
<Button type="primary">Soumettre les changements</Button>
</form>
<Button type="danger" onClick={this.logState} />
</Dashboard>
)
}
}
export default EditUser
```
```
import React, { Component } from 'react'
import InterestBox from './InterestBox'
import Axios from 'axios'
export class InterestList extends Component {
constructor(props) {
super(props);
this.state = {pinterests: []}
this.pinterestRefs = React.createRef()
this.pinterestRefs.current = [];
}
componentDidMount() {
Axios.get('http://localhost:8000/api/interests')
.then((success) => {
this.setState({pinterests: success.data.data.interests});
})
}
componentDidUpdate(prevProps) {
console.log(JSON.stringify(prevProps));
console.log(JSON.stringify(this.props))
if(this.props.alreadyChecked != prevProps.alreadyChecked) {
this.props.alreadyChecked.forEach((item) => {
this.pinterestRefs.current.forEach((pinterest) => {
if(item == pinterest.props.id) {
console.log(pinterest)
pinterest.handleClick();
}
})
console.log(item)
})
}
console.log(this.pin)
}
render() {
return (
<React.Fragment>
{Object.keys(this.state.pinterests).map((interest, i) => {
var pinterest = this.state.pinterests[interest];
var callbackRef = node => this.pinterestRefs.current[i] = node;
return <InterestBox id={pinterest.id} onClick={this.props.onClick} icon={pinterest.picture_src} title={pinterest.name} ref={callbackRef} />
})}
</React.Fragment>
)
}
}
export default InterestList
```
```
import React, { Component } from 'react'
export class InterestBox extends Component {
constructor(props) {
super(props);
this.images = require('../../img/interests/*.svg');
this.state = {activated: false};
this.interest_box_content = React.createRef();
this.interest_text = React.createRef();
this.handleClick = this.handleClick.bind(this);
this.updateDimensions = this.updateDimensions.bind(this);
}
handleClick() {
console.log('hoppity hippity you clicky')
this.props.onClick(this.props.id, this.props.title);
this.setState(prevState => ({
activated: !prevState.activated
}))
}
updateDimensions() {
console.log((window.getComputedStyle(this.refs.interest_box_content).width))
this.refs.interest_text = (window.getComputedStyle(this.refs.interest_box_content).width)
}
render() {
return (
<div className="column is-one-fifth-desktop is-half-touch">
<div className="interest-box">
<div className="interest-box-adjuster">
<div ref={"interest_box_content"} className={"interest-box-content " + (this.state.activated == true ? 'interest-box-activated' : '')} onClick={this.handleClick}>
<img className="interest-icon" src={this.images[this.props.icon]} style={{'height': '50%'}}></img>
<i className="activated-icon fas fa-check"></i>
<span ref={"interest_text"} className="interest-text">{this.props.title}</span>
</div>
</div>
</div>
</div>
)
}
}
export default InterestBox
```
you have initialized interest as an array using []
but then, you are updating it as a map state.interests[mid] = name;
Note: JS is not type-safe. after the above statement, interests no longer remained an array
That's the reason why on console you are able to see it being populated but with an array length of 0. that's because you are outputting an object now and not an array.

Changing parent state after updating childs prop component in React?

I'm newish to react. I have a fetch call in my App Component that I assign to a state. I pass that state as a prop along with a function to make a post to a child component. In my child component you can post/delete to alter the props, currently don't have a push() to add the new contact/prop. Is there a way to alter the parent component's state after I change the childs props? is there a better way to do this?
I'm trying to get the post action to update the state on the App.
App code
class App extends Component {
constructor() {
super();
this.state= {
contacts:[],
addModalShow: false,
modalIsOpen: false
}
}
componentDidMount() {
var request = new Request('http://localhost:3000/', {
method: "GET",
});
fetch(request)
.then((res) => {
res.json()
.then((data) => {
this.setState({
contacts: data.rows
})
})
})
}
toggleModal() {
this.setState({
modalIsOpen: ! this.state.modalIsOpen
})
}
addContact(event) {
this.toggleModal()
event.preventDefault();
let contactData = {
first: this.refs.first.value,
last: this.refs.last.value,
phone: this.refs.phone.value,
email: this.refs.email.value,
};
var request = new Request('http://localhost:3000/add', {
method: "POST",
headers: new Headers({ 'Content-Type': 'application/json' }),
body: JSON.stringify(contactData)
});
console.log(this.state)
fetch(request)
.then((res) => {
res.json()
.then((data) => {
})
})
.catch((err) => {
console.log(err)
})
}
render() {
return (
<Container>
{console.log(this.state)}
<AddContact addContact={this.addContact} contacts={this.state.contacts} />
<ContactList contacts={this.state.contacts} />
<Contacts contacts={this.state.contacts}/>
</Container>
);
}
}
export default App;
Child component
class AddContact extends Component {
constructor(props) {
super(props);
this.state = {
contacts: [],
modalIsOpen: false,
}
}
toggleModal() {
this.setState({
modalIsOpen: ! this.state.modalIsOpen
})
}
render() {
return(
<Container>
<div className='header'>
<h1>
My Contacts
<button className='addContactButton' onClick={this.toggleModal.bind(this)}>+</button>
</h1>
<hr />
</div>
<Modal isOpen={this.state.modalIsOpen}>
<form ref='addContact' >
<div className='addContactHeader'>
<button className='saveButton' onClick={this.props.addContact.bind(this)}>Save</button>
<button className='cancelButton' onClick={this.toggleModal.bind(this)}>Cancel</button>
</div>
<div id="circle">
Add Photo
</div>
<div className="inputFields">
<div className='nameInputs'>
<input type='text' ref='first' placeholder='first name' />
<input type='text' ref='last' placeholder='last name' />
</div>
<div className='extraInputs' >
<input type='text' ref='phone' placeholder='phone' />
<input type='text' ref='email' placeholder='email' />
</div>
</div>
</form>
</Modal>
</Container>
)
}
}
Thanks for your time
You could use a callback function in order to update the state on the parent component (Another approach would be to use Redux updating the value in the Store, that way both components could have access to the value), here's how you could use the callback (With a little bit of ES6 refactor):
App:
class App extends Component {
state= {
contacts:[],
addModalShow: false,
modalIsOpen: false
}
componentDidMount() {
let request = new Request('http://localhost:3000/', {
method: "GET",
});
fetch(request)
.then((res) => {
res.json()
.then((data) => { this.setState({ contacts: data.rows }) })
})
}
toggleModal = () => {
this.setState({ modalIsOpen: ! this.state.modalIsOpen })
};
addContact = event => {
this.toggleModal()
event.preventDefault();
let contactData = {
first: this.refs.first.value,
last: this.refs.last.value,
phone: this.refs.phone.value,
email: this.refs.email.value,
};
let request = new Request('http://localhost:3000/add', {
method: "POST",
headers: new Headers({ 'Content-Type': 'application/json' }),
body: JSON.stringify(contactData)
});
fetch(request)
.then((res) => {
res.json()
.then((data) => {
})
})
.catch((err) => {
console.log(err)
})
};
changeContacts = (newData) => {
this.setState({ contacts: newData });
};
render() {
const { contacts } = this.state;
return (
<Container>
<AddContact
addContact={this.addContact}
contacts={contacts}
onChildAction={this.changeContacts}
/>
<ContactList contacts={contacts} />
<Contacts contacts={contacts}/>
</Container>
);
}
}
export default App;
AddContacts:
class AddContact extends Component {
state = {
contacts: [],
modalIsOpen: false,
}
toggleModal = () => {
this.setState({ modalIsOpen: ! this.state.modalIsOpen })
};
// Here is where you'll send the info for the change of the prop
changeProp = e => {
const { onChildAction } = this.props;
onChildAction('Your new state/prop value here')
addContact(e);
};
render() {
const { changeProp } = this.props;
const { modalIsOpen } = this.state;
return(
<Container>
<div className='header'>
<h1>My Contacts
<button className='addContactButton' onClick={this.toggleModal}>+</button>
</h1>
<hr />
</div>
<Modal isOpen={modalIsOpen}>
<form ref='addContact' >
<div className='addContactHeader'>
<button className='saveButton' onClick={changeProp}>Save</button>
<button className='cancelButton' onClick={this.toggleModal}>Cancel</button>
</div>
<div id="circle">Add Photo</div>
<div className="inputFields">
<div className='nameInputs'>
<input type='text' ref='first' placeholder='first name' />
<input type='text' ref='last' placeholder='last name' />
</div>
<div className='extraInputs' >
<input type='text' ref='phone' placeholder='phone' />
<input type='text' ref='email' placeholder='email' />
</div>
</div>
</form>
</Modal>
</Container>
)
}
}
The last thing you need to do is decide where you want the change of the state/prop to be fire. Hope this helps.
to handle the parent from child you need to bind this to the child
Parent Component
class Component extends React.Component {
constructor(props) {
super(props)
this.state= {
contacts:[],
addModalShow: false,
modalIsOpen: false
}
this.addContact = this.addContact.bind(this);
}
render() {
...
return <AddContact addContact = {this.addContact} />
}
addContact(event) {
...
alert('one contact added');
...}
}
inside AddContact Component :
you can call this.props.addContact() to excute the parent function

How to structure my API call, and where to put the key and query?

I am trying to structure my API call to the openweatherapi properly, just trying to create a simple weather app, where upon the user entering a city the forecast is rendered to the page. This is what I have so far, also trying to prevent the default action where the page refreshes when the button is pressed. I am using react.
class App extends Component {
getWeatherData = (userInput, event) => {
event.preventDefault();
axios({
url: "http://openweathermap.org/data/2.5/weather/",
method: "GET",
dataType: "json",
data: {
q: userInput,
API_KEY: "d108038ec889cfe762230283abaa7c7b"
}
}).then(res => {
console.log(res);
this.setState({});
});
};
./Form. js is as follows
class Form extends Component {
render() {
return (
<div>
<form onSubmit={(this.props.getWeather, e)}>
<input type="text" name="city" placeholder="City..." />
<input type="text" name="country" placeholder="Country" />
<button>Get Weather</button>
</form>
</div>
);
}
}
Error:
./src/Form.js
Line 7: 'e' is not defined no-undef
Using class components, I would do something like this :
(each class/function should be split in a different file)
/**
* This is just a helper to encapsulate the weather fetching logic
*/
function getWeatherFromInput({ city, country }) {
const query = `${city},${country}`;
return axios({
method: 'GET',
url: `http://openweathermap.org/data/2.5/weather?${query}`,
responseType: 'json'
});
}
/**
* Here is the specific form
*/
export class WeatherForm extends React.Component {
constructor(props) {
super(props);
this.state = {
city: '',
country: ''
};
}
handleSubmit = (event) => {
event.preventDefault();
this.props.onSubmit(this.state);
};
handleInputChange = (event) => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
render() {
const { city, country } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
name='city'
value={city}
onChange={this.handleInputChange}
placeholder='City...'
/>
<input
type='text'
name='country'
value={country}
onChange={this.handleInputChange}
placeholder='Country'
/>
<button type='submit'>Get weather</button>
</form>
);
}
}
/**
* And how you use it in your App
*/
export class App extends React.Component {
constructor() {
this.state = {
weather: {}
};
}
/**
* The userInput is provided by the WeatherForm
*/
handleSubmit = (userInput) => {
getWeatherFromInput(userInput).then((response) => {
this.setState({ weather: response.data });
});
};
render() {
return <WeatherForm onSubmit={handleSubmit} />;
}
}
You can just move your form to your app class, passing up form data between components doenst work perfectly in react.
class App extends Component {
getWeatherData = (event) => {
const userInput = {
event.target.city.value,
event.target.country.value
}
event.preventDefault();
axios({
url: "http://openweathermap.org/data/2.5/weather/",
method: "GET",
dataType: "json",
data: {
q: userInput,
API_KEY: "d108038ec889cfe762230283abaa7c7b"
}
}).then(res => {
console.log(res);
this.setState({});
});
render() {
return (
<div>
<form onSubmit={this.getWeatherData}>
<input type="text" name="city" placeholder="City..." />
<input type="text" name="country" placeholder="Country" />
<button>Get Weather</button>
</form>
</div>
);
}
}
You also dont need to specify the userInput as a parameter you can set inside your function by accessing the values with the event keyword.

Categories

Resources