The below is my code.
What i am doing is a currency converter app by fetching external API. It is guaranteed process.env.REACT_APP_DATA_SOURCE is always correct.
The problem here is: If I change the currency, either inputCurrency or outputCurrency, I need to click "Submit" button twice instead of once to display a correct answer. Why is it the case?
I can't come up with any better wording so I used "delay" in the heading.
Thank you!
import './App.css';
import { useState, useEffect } from 'react';
import { Select, Button, ButtonGroup } from '#chakra-ui/react';
function App() {
const [exchangeRate, setExchangeRate] = useState(7.8491);
const [inputCurrency, setInputCurrency] = useState('USD');
const [inputAmount, setInputAmount] = useState(1);
const [outputCurrency, setOutputCurrency] = useState('HKD');
const [outputAmount, setOutputAmount] = useState(7.8491);
useEffect(() => {
const fetchData = async (url) => {
await fetch(url)
.then((response) => response.json())
.then((data) => setExchangeRate(data.conversion_rates[outputCurrency]));
};
try {
let url = `${process.env.REACT_APP_DATA_SOURCE}${inputCurrency}`;
fetchData(url);
} catch (err) {
console.log(err);
}
}, [inputCurrency, outputCurrency]);
const handleSubmit = async (e) => {
e.preventDefault();
setInputCurrency(e.target.inputCurrency.value);
setInputAmount(e.target.inputAmount.value);
setOutputCurrency(e.target.outputCurrency.value);
let result = inputAmount * exchangeRate;
setOutputAmount(result);
};
return (
<div className="main-body">
<form onSubmit={handleSubmit}>
<h3>Set input amount:</h3>
<input className="inputAmount" name="inputAmount" type="number" />
<h3>Set input currency:</h3>
<Select name="inputCurrency">
<option value="USD">USD</option>
<option value="HKD">HKD</option>
<option value="CNY">CNY</option>
<option value="GBP">GBP</option>
<option value="CAD">CAD</option>
</Select>
<h3>Set output currency:</h3>
<Select name="outputCurrency">
<option value="USD">USD</option>
<option value="HKD">HKD</option>
<option value="CNY">CNY</option>
<option value="GBP">GBP</option>
<option value="CAD">CAD</option>
</Select>
<Button colorScheme="blue" type="submit">
Submit
</Button>
</form>
<h3>
{inputAmount} {inputCurrency} is equal to:
</h3>
<h3>
{outputAmount} {outputCurrency}
</h3>
</div>
);
}
export default App;
You are calculating the output amount at the wrong place. First, you update the inputCurrency and outputCurrency in handleSubmit. This means the useEffect will be 'triggered' and the new exchange rate will be fetched. But that's not gonna happen immediately. Definitely not before result is calculated.
const handleSubmit = async (e) => {
e.preventDefault();
setInputCurrency(e.target.inputCurrency.value);
setInputAmount(e.target.inputAmount.value);
setOutputCurrency(e.target.outputCurrency.value);
//This will ALWAYS use the old previous exchange rate.
let result = inputAmount * exchangeRate;
setOutputAmount(result);
};
What you want is to recalculate outputAmount whenever the exchangeRate or inputAmount changes. You can use another useEffect like:
useEffect(() => {
//Take these out from handleSubmit.
let result = inputAmount * exchangeRate;
setOutputAmount(result);
}, [inputAmount, exchangeRate])
Related
I'm trying to add a Leader to my DB via a post.
I want to select a branch so the leader is linked to that branch.
but When I select the branch from the select box the Id does not get filled and I get the following error:
.branchId: [,…]
0: "The JSON value could not be converted to System.Guid. Path: $.branchId | LineNumber: 0 | BytePositionInLine: 30."
been stuck for a day now, help is muich appreciated
import React, {useState, useEffect} from 'react'
import axios from 'axios'
const LeadersPost = () => {
const [totem, setTotem] = useState('');
const [branchId, setBranchId] = useState('')
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async() => {
try{
const {data: response} = await axios.get('https://localhost:7070/api/Branches');
setData(response);
} catch (error) {
console.error(error.message);
}
}
fetchData();
}, []);
const onSubmit = async (e) => {
e.preventDefault();
const data = {
totem : totem,
branchId : branchId
}
try{
await axios.post('https://localhost:7070/api/Leaders', data)
.then(res => {
setData(res.data);
setTotem('');
setBranchId('');
})
} catch (error){
console.error(error.message);
}
}
return(
<div className='container mt-2'>
<h2>Leaders Post Request</h2>
<form onSubmit={onSubmit}>
<div className='mb-2 mt-3'>
<input
type={'text'}
placeholder='Leader Totem'
className='form-control'
value={totem}
onChange={e => {
setTotem(e.target.value)
}} />
<select className="form-control" aria-label="Default select example">
<option>Choose a branch</option>
{
data.map(branch =>
<option
onChange={ e => {
setBranchId(e.target.value)
}}>
{branch.id}
</option>)
}
</select>
<button type='submit' className='btn btn-primary'>Create</button>
</div>
</form>
</div>
)
}
export default LeadersPost
I don't believe the option fires an onchange event, I could be wrong but if my memory serves me correctly it doesn't. Also just checked MDN web docs and I may be correct in that.
However, I also believe the value of the option not being set would also cause this to happen. You're just setting a textConext on the event, so you could make it work potentially by that too but you may want to take a look at this answer here for select boxes in react.
I'm trying to submit a form that sends a http request onSubmit, but I'm getting undefined when setting the state on the values. I'm not sure why the values are not being passed upon click and being set with the set...() function.
Below is the code of that component. Upon first submit action I get an error because the "surveyUserAnswers" are undefined, but in the next submissions it works. Not sure why? Could someone advise.
I'm very new to typescript and react hooks, so excuse my code! thanks
import React, { useRef, useState } from "react";
import Loader from "../UI/loader/loader";
import axios from "axios";
import "./surveybox.css";
interface surveryAnswer {
id: number;
answers: string[];
}
const SurveyBox: React.FC = () => {
const [surveyUserAnswers, setSurveyUserAnswers] = useState<surveryAnswer>();
const [loading, setLoading] = useState(false);
const programmingQRef = useRef<HTMLSelectElement>(null);
const skillsQRef = useRef<HTMLSelectElement>(null);
const stateManagementQRef = useRef<HTMLSelectElement>(null);
const programmerTypeQRef = useRef<HTMLSelectElement>(null);
const onSubmitSurvey = (e: React.FormEvent): void => {
e.preventDefault();
setLoading((prevLoading) => !prevLoading);
setSurveyUserAnswers({
id: Math.random(),
answers: [
programmerTypeQRef.current!.value,
skillsQRef.current!.value,
stateManagementQRef.current!.value,
programmerTypeQRef.current!.value,
],
});
axios
.post(`${DB_URL}/users-answers.json`, surveyUserAnswers)
.then((res) => {
setLoading((prevLoading) => !prevLoading);
})
.catch((error) => {
console.log(error);
setLoading((prevLoading) => !prevLoading);
});
};
return (
<div className="surveybox-container">
{loading ? (
<div className={"loader-holder"}>
<Loader />
</div>
) : (
<React.Fragment>
<h2>Quick survey!</h2>
<form action="submit" onSubmit={onSubmitSurvey}>
<label>favorite programming framework?</label>
<select ref={programmingQRef} name="programming">
<option value="React">React</option>
<option value="Vue">Vue</option>
<option value="Angular">Angular</option>
<option value="None of the above">None of the above</option>
</select>
<br></br>
<label>what a junior developer should have?</label>
<select ref={skillsQRef} name="skills">
<option value="Eagerness to lear">Eagerness to learn</option>
<option value="CS Degree">CS Degree</option>
<option value="Commercial experience">
Commercial experience
</option>
<option value="Portfolio">Portfolio</option>
</select>
<br></br>
<label>Redux or Context Api?</label>
<select ref={stateManagementQRef} name="state-management">
<option value="Redux">Redux</option>
<option value="Context Api">Context Api</option>
</select>
<br></br>
<label>Backend, Frontend, Mobile?</label>
<select ref={programmerTypeQRef} name="profession">
<option value="Back-end">back-end</option>
<option value="Front-end">front-end</option>
<option value="mobile">mobile</option>
</select>
<br></br>
<button type="submit">submit</button>
</form>
</React.Fragment>
)}
</div>
);
};
export default SurveyBox;
Setting the state is an async action, and the updated state would only be available at the next render.
In your case, the default state is undefined, and this is what you send at the 1st submit. The state is now updated, and when you submit again, you send the previous answer, and so on...
To solve this, prepare a const (newAnswer), and set it to the state, and use it in the api call.
Note: in your case, you're not using the surveyUserAnswers at all, so you can remove this state entirely.
const onSubmitSurvey = (e: React.FormEvent): void => {
e.preventDefault();
setLoading((prevLoading) => !prevLoading);
const newAnswer = {
id: Math.random(),
answers: [
programmerTypeQRef.current!.value,
skillsQRef.current!.value,
stateManagementQRef.current!.value,
programmerTypeQRef.current!.value,
],
}
setSurveyUserAnswers(newAnswer);
axios
.post(`${DB_URL}/users-answers.json`, newAnswer)
.then((res) => {
setLoading((prevLoading) => !prevLoading);
})
.catch((error) => {
console.log(error);
setLoading((prevLoading) => !prevLoading);
});
};
I'm noobie on React and I want to fill a <select>
The problem that I have is when I want to click one of my items... dropdown only show different options if I put my items harcoded. Here's my code
Parent component
import React, { Fragment, useState, useEffect } from "react";
import Country from "./Country";
const CountriesList = ({ handleOnChange }) => {
const [countriesLoaded, setCountriesLoaded] = useState(false);
const [countriesList, setCountriesList] = useState([]);
const getCountries = async () => {
const api = "https://restcountries.eu/rest/v2/all";
const response = await fetch(api);
const countrieslst = await response.json();
setCountriesList(countrieslst);
setCountriesLoaded(true);
};
useEffect(() => {
getCountries();
}, [countriesList]);
return (
<Fragment>
<select id="country" name="country" onChange={handleOnChange}>
<option value="">-- Select a country --</option>
{countriesLoaded
? countriesList.map((country) => (
<Country key={country.alpha2Code} countryItem={country} />
))
: null}
</select>
</Fragment>
);
};
export default CountriesList;
child component
import React from "react";
const Country = ({ country }) => {
return <option value={country.alpha2Code}>{country.name}</option>;
};
export default Country;
If I check DOM it's ok but only shows my first option
Thnx 4 support and have a nice day!
[Edit]
just add <select id="country" name="country" onChange={handleOnChange} style={{display: 'block'}}> in your code. you will be able to view a select box rendering data
here is the link i made few changes in your code as well but this is optional:
https://codesandbox.io/s/nd58i?file=/src/components/Form.jsx
When we enter some value in text box and currency in the fromCurrency dropdown field and select appropriate currency in the toCurrency dropdown field, how do we display rates in the toCurrency based on that selection ?
https://codesandbox.io/s/rough-http-jc35u?file=/src/App.js
import React, { useState, useEffect } from "react";
import "./styles.css";
const axios = require("axios");
function App() {
const [sourceCurrency, setSourceCurrency] = useState("");
const [targetCurrency, setTargetCurrency] = useState("");
const [ratesList, setRatesList] = useState([]);
const [selectFromCurrency, setFromSourceCurrency] = useState("");
const [selectToCurrency, setSelectToCurrency] = useState("");
const getSourceCurrency = (source) => {
setSourceCurrency(source);
};
const getTargetCurrency = (target) => {
setTargetCurrency(target);
};
useEffect(() => {
const fetchData = async () => {
try {
const data = await axios.get("https://api.exchangeratesapi.io/latest");
setRatesList(data);
console.log(data);
} catch (e) {
console.log(e);
}
};
fetchData();
}, []);
const selectSourceCurrency = (sourceCurr) => {
setFromSourceCurrency(sourceCurr);
};
const selectTargetCurrency = (targetCurr) => {
setSelectToCurrency(targetCurr);
};
const convertRate = () => {
const rateCalc = sourceCurrency * targetCurrency;
console.log("print rate: " + rateCalc);
// how can we the rates list here and based on the selection ?
};
return (
<div className="App">
<div className="globalCurrencyConverter">
<h2>Currency Converter</h2>
<div className="container box">
<label>
<input
name="sourceCurrency"
type="text"
placeholder="fromCurrency"
onChange={(event) => getSourceCurrency(event.target.value)}
/>
<select
className="fromCurrency"
defaultValue={"DEFAULT"}
onChange={(event) => selectSourceCurrency(event.target.value)}
>
<option>USD</option>
<option value="DEFAULT">AUD</option>
<option>NZD</option>
<option>INR</option>
<option>UAE Dirham</option>
</select>
</label>
<label>
<input
name="targetCurrency"
type="text"
placeholder="toCurrency"
onChange={(event) => getTargetCurrency(event.target.value)}
/>
<select
className="toCurrency"
onChange={(event) => selectTargetCurrency(event.target.value)}
>
<option>USD</option>
<option>AUD</option>
<option>NZD</option>
<option>INR</option>
<option>UAE Dirham</option>
</select>
</label>
<div className="recordBtn">
<button name="convert" onClick={(event) => convertRate()}>
Convert
</button>
</div>
</div>
</div>
</div>
);
}
export default App;
I will assume that you can handle the population of those select fields with currencies yourself and instead will show you how to solve the actual conversion problem. So we shall leave those select options hardcoded as they are in your code. e.g. (USD, NZD, AUD etc.)
So we won't actually even need that useEffect for this test since we simply hardcode the currencies. Personally, I like to solve my React problems with as little re-renders as possible. So the way I would approach this specific problem is by creating references to all 4 of your fields. It will allow us to access their values any time. Check out useRef().
Then when someone enters all the info and clicks that "Convert" button, I would call your API and pass it the selected currency as base currency. like so
https://api.exchangeratesapi.io/latest?base=USD
Once axios fetches the data on it, it is just a matter of some basic match and assignment of the proper value to the "To Currency" field. So here is a working example along with a Sandbox:
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";
const axios = require("axios");
function App() {
const from_select = useRef(),
to_select = useRef(),
from_input = useRef(),
to_input = useRef();
useEffect(() => {
const fetchData = async () => {
try {
const data = await axios.get("https://api.exchangeratesapi.io/latest");
//setRatesList(data);
console.log(data);
} catch (e) {
console.log(e);
}
};
fetchData();
}, []);
const convertRate = () => {
const from_cur = from_select.current.value;
const to_cur = to_select.current.value;
const from_amount = from_input.current.value;
console.log(from_cur);
axios
.get("https://api.exchangeratesapi.io/latest?base=" + from_cur)
.then((result) => {
const rate = result.data.rates[to_cur];
const converted_amount = rate * from_amount;
to_input.current.value = converted_amount;
});
};
return (
<div className="App">
<div className="globalCurrencyConverter">
<h2>Currency Converter</h2>
<div className="container box">
<label>
<input
ref={from_input}
name="sourceCurrency"
type="text"
placeholder="fromCurrency"
/>
<select
ref={from_select}
className="fromCurrency"
defaultValue={"USD"}
>
<option value="USD">USD</option>
<option value="AUD">AUD</option>
<option value="NZD">NZD</option>
</select>
</label>
{" -> "}
<label>
<input
ref={to_input}
name="targetCurrency"
type="text"
placeholder="toCurrency"
/>
<select ref={to_select} className="toCurrency" defaultValue="AUD">
<option value="USD">USD</option>
<option value="AUD">AUD</option>
<option value="NZD">NZD</option>
<option value="RUB">RUB</option>
<option value="EUR">EUR</option>
</select>
</label>
<div className="recordBtn">
<button name="convert" onClick={convertRate}>
Convert
</button>
</div>
</div>
</div>
</div>
);
}
export default App;
your ratesList would be an object extracted from data.data.rates with country keys and rate values set at initial useEffect as:
useEffect(() => {
const fetchData = async () => {
try {
const data = await axios.get("https://api.exchangeratesapi.io/latest");
setRatesList(data.data.rates);
} catch (e) {
console.log(e);
}
};
fetchData();
}, []);
your convertRate validates first if sourceCurrency is a number and if there is a ratesList. To calculate the conversion you need to multiply the amount value by the ratio (toCurrency/FromCurrency):
const convertRate = () => {
if (isNaN(sourceCurrency) || !ratesList) return;
setTargetCurrency(
(ratesList[selectToCurrency] / ratesList[selectFromCurrency]) *
sourceCurrency
);
};
set initial values for currencies:
const [selectFromCurrency, setFromSourceCurrency] = useState("USD");
const [selectToCurrency, setSelectToCurrency] = useState("NZD");
and remove default values for your select and input values. Instead pass the state value to have a controlled input like:
<select
className="fromCurrency"
value={selectFromCurrency}
onChange={(event) => selectSourceCurrency(event.target.value)}
>
<option>USD</option>
<option>AUD</option>
<option>NZD</option>
<option>INR</option>
<option>PLN</option>
</select>
for your toCurrency input make it a disabled field, since you don't user to type values on it:
<input
name="targetCurrency"
value={targetCurrency}
disabled
type="text"
placeholder="toCurrency"
/>
working demo:
note: UAE Dirham doesn't match at API response so changed for PLN
I've been working on this project for the last couple of hours and I was pretty sure that this final hour would be my last. No errors are appearing. My thinking is that when I pick a hero from the drop down, the page will update depending on my choice. I may have something that isn't firing that I'm not picking up on.
import React, {useEffect, useState} from 'react'
import axios from 'axios'
require("regenerator-runtime/runtime");
const App = () => {
const [hero, selectedHero] = useState(
'Select a Hero'
);
const handleChange = event => selectedHero(event.target.value);
return(
<HeroSelect heroSelect={hero} onChangeHeadline={handleChange} />
);
};
const HeroSelect = ({heroSelect, onChangeHeadline}) => {
const [data, setData] = useState({heroes: []});
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://api.opendota.com/api/heroStats',
);
setData({...data, heroes: result.data});
};
fetchData();
}, []);
return (
<div>
<h1>{heroSelect}</h1>
<select>
{data.heroes.map(item => (
<option key={item.id} value={heroSelect} onChange={onChangeHeadline} >
{item.localized_name}
</option>
))}
</select>
</div>
)
};
export default App
Define your onChange={onChangeHeadline} on Select tag not on option tag
<select onChange={onChangeHeadline}>
{data.heroes.map(item => (
<option key={item.id} value={item.localized_name}>
{item.localized_name}
</option>
))}
</select>
You should be firing your onChange event on the select tag itself.
<select onChange={onChangeHeadline} >
.....
.....
</select>
I reckon you didn't declare an onChange on the select.
Using This method:
<select id="lang" onChange={this.change} value={this.state.value}>
<option value="select">Select</option>
<option value="Java">Java</option>
<option value="C++">C++</option>
</select>