React selection option value change the variable data - javascript

I'm trying to become a front-end developer, so I'm creating a project with companies info. I tried to find on YouTube and here, but still I couldn't understand.
I want to use on Change to show the result, but How I pass the option value to the variable?
import React, { Component } from "react";
class BusinessCard extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
company: null,
};
}
async componentDidMount() {
let companyCod = "MSFT"; // I want receive the option value here
let companyUrl =
"https://www.alphavantage.co/query?function=OVERVIEW&symbol=" +
companyCod +
"&apikey=YOUR-API-KEY";
let response = await fetch(companyUrl);
let data = await response.json();
this.setState({ company: data, loading: false });
}
render() {
if (this.state.loading) {
return <div>loading</div>;
}
return (
<div>
<select>
<option value="MSFT">MSFT</option>
<option value="AAPL">AAPL</option>
<option value="IBM">IBM</option>
</select>
<h1>Company: {this.state.company.Name}</h1>
<h1>Symbol: {this.state.company.Symbol}</h1>
</div>
);
}
}

You could put the countryCode in your component state, and move the componentDidMount code into a separate function that you call both in componentDidMount and when the select changes.
Example
import React, { Component } from "react";
export default class BusinessCard extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
company: null,
companyCode: "MSFT"
};
}
loadCompany = async (companyCode) => {
let companyUrl =
"https://www.alphavantage.co/query?function=OVERVIEW&symbol=" +
companyCode +
"&apikey=YOUR-API-KEY";
let response = await fetch(companyUrl);
let data = await response.json();
this.setState({ company: data, loading: false });
}
componentDidMount() {
this.loadCompany(this.state.companyCode);
}
handleChange = (e) => {
const companyCode = e.target.value;
this.setState({ companyCode });
this.loadCompany(companyCode);
};
render() {
if (this.state.loading) {
return <div>loading</div>;
}
return (
<div>
<select
value={this.state.companyCode}
onChange={this.handleChange}
>
<option value="MSFT">MSFT</option>
<option value="AAPL">AAPL</option>
<option value="IBM">IBM</option>
</select>
<h1>Company: {this.state.company.Name}</h1>
<h1>Symbol: {this.state.company.Symbol}</h1>
</div>
);
}
}

Related

How to make live search on this name react js?

I am trying to make live search for name in table but i can't make live search i don't know how to do this i wrote my code like this as i mentioned please help me how to make live search on name field foe table and in Search Page i used onSubmit={this.props.loaddata like this thanks
import React, { Component } from "react";
import Search from "../../views/Cars/Search";
class Search1 extends Component {
constructor(props) {
super(props);
this.state = {
query: []
};
}
// Get Data from filter date
getData = async e => {
try {
const search = e.target.elements.search.value;
e.preventDefault();
const res = await fetch(`https://swapi.co/api/people/?search=${search}`);
const query = await res.json();
console.log(query);
this.setState({
query: query.results
});
} catch (e) {
console.log(e);
}
};
async componentDidMount() {
// let authToken = localStorage.getItem("Token");
try {
const res = await fetch(`https://swapi.co/api/people/`);
const query = await res.json();
// console.log(movie);
this.setState({
query: query.results
});
} catch (e) {
console.log(e);
}
}
render() {
const options = this.state.query.map(r => <li key={r.id}>{r.name}</li>);
return (
<div>
<Search loaddata={this.getData} />
{options}
</div>
);
}
}
export default Search1;
Genrally You can try React-Search
import Search from 'react-search'
import ReactDOM from 'react-dom'
import React, { Component, PropTypes } from 'react'
class TestComponent extends Component {
HiItems(items) {
console.log(items)
}
render () {
let items = [
{ id: 0, value: 'ruby' },
{ id: 1, value: 'javascript' },
{ id: 2, value: 'lua' },
{ id: 3, value: 'go' },
{ id: 4, value: 'julia' }
]
return (
<div>
<Search items={items} />
<Search items={items}
placeholder='Pick your language'
maxSelected={3}
multiple={true}
onItemsChanged={this.HiItems.bind(this)} />
</div>
)
}
}
Made few changes to your component. Send e.target.value from your child component
class Search1 extends Component {
constructor(props) {
super(props);
this.state = {
query: []
};
}
// Get Data from filter date
getData = search => {
const url = `https://swapi.co/api/people${search ? `/?search=${search}` : ``}`;
// e.preventDefault();
fetch(url)
.then(res => res.json())
.then(data =>
this.setState({
query: data.results || []
})).catch(e => console.log(e));
};
async componentDidMount() {
// let authToken = localStorage.getItem("Token");
this.getData();
}
render() {
const options = this.state.query.map(r => <li key={r.id}>{r.name}</li>);
return (
<div>
<Search loaddata={this.getData} />
{options}
</div>
);
}
}
export default Search1;
For Gettind Data from Api you can follow this code of react-search
import Search from 'react-search'
import ReactDOM from 'react-dom'
import React, { Component, PropTypes } from 'react'
class TestComponent extends Component {
constructor (props) {
super(props)
this.state = { repos: [] }
}
getItemsAsync(searchValue, cb) {
let url = `https://api.github.com/search/repositories?q=${searchValue}&language=javascript`
fetch(url).then( (response) => {
return response.json();
}).then((results) => {
if(results.items != undefined){
let items = results.items.map( (res, i) => { return { id: i, value: res.full_name } })
this.setState({ repos: items })
cb(searchValue)
}
});
}
render () {
return (
<div>
<Search items={this.state.repos}
multiple={true}
getItemsAsync={this.getItemsAsync.bind(this)}
onItemsChanged={this.HiItems.bind(this)} />
</div>
)
}

State is being initialized with [object Object] in setState

In the async function below, I call stationData just to confirm that I'm passing an array of objects into bartData (which is just an empty array). Attached is a response of the array of Objects that I am receiving. However, when trying to use this.state.bartData (to confirm that it does have the array of objects), my return function is returning bartData as undefined. Any ideas?
import React from 'react';
const bartKey = process.env.REACT_API_BART_API_KEY;
class StationBaseRoutes extends React.Component{
constructor(props){
super(props);
this.state = {
isLoading: true,
station: [],
stationAbbv: 'ALL',
destination: '',
bartData: []
}
}
componentDidMount(){
this.getAllStationRoutes();
}
async getAllStationRoutes(){
try{
setInterval(async () => {
const response = await fetch(`http://api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.stationAbbv}&key=${bartKey}&json=y`);
const jsonResponse = await response.json();
const apiData = jsonResponse.root;
const stationData = apiData.station;
console.log(stationData);
this.setState(({
isLoading: false,
bartData: stationData
}), () => {
console.log(`Callback: ${this.state.bartData}`)
})
}, 20000)
} catch(error){
console.log(error);
}
}
getRoutes = () => {
console.log(`bartData: ${this.bartData}`)
}
render(){
const {station, destination} = this.state;
return(
<div>
<h2>Calling get routes: {this.getRoutes()}</h2>
<h2>Origin: {station}</h2>
<h3>Destination: {destination}</h3>
</div>
)
}
}
export default StationBaseRoutes;
Responses: https://imgur.com/gallery/Luk9MCX
There's a couple of bugs here.
First of all, getRoutes() is using this.bartData instead of this.state.bartData
Secondly, all your objects in console.log are being converted to strings. You can change it to
console.log('bartData:', this.state.bartData);
to be able to see the actual data.
I was unable to get the Bart API to work in a codesandbox, so I had to mock the API... however, the data is still structured the same.
On that note, the API is working as expected, you just need to map over the objects in the this.state.bartData array and deconstruct the properties you want to show.
Working example: https://codesandbox.io/s/031pn7w680
import map from "lodash/map";
import React, { Component, Fragment } from "react";
import { fakeAPI } from "../../api/fakeAPI";
class StationBaseRoutes extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
station: [],
stationAbbv: "ALL",
destination: "",
bartData: []
};
this.getAllStationRoutes = this.getAllStationRoutes.bind(this);
}
componentDidMount() {
this.getAllStationRoutes();
}
async getAllStationRoutes() {
try {
const res = await fakeAPI.get();
const apiData = res.data.root;
const stationData = apiData.station;
this.setState({
isLoading: false,
bartData: stationData
});
} catch (error) {
console.log(error);
}
}
render() {
const { bartData, isLoading } = this.state;
return (
<div className="app-container">
{isLoading ? (
<p className="t-a-c">Loading...</p>
) : (
<Fragment>
<h1 className="t-a-c">Bart Stations</h1>
{map(bartData, ({ name, etd }) => (
<div className="jumbotron station" key={name}>
<h1>Origin: {name}</h1>
{map(etd, ({ destination }) => (
<li key={destination}>Destination: {destination}</li>
))}
</div>
))}
<pre className="preview">
<code>{JSON.stringify(bartData, null, 4)}</code>
</pre>
</Fragment>
)}
</div>
);
}
}
export default StationBaseRoutes;

Load data before rendering child elements React

I am trying to generate a list of selector options based on external JSON data. The code here is mostly good, except that part of it is being called before the data is loading resulting in no children being appended. I am sure there is a way to implement this but I'm not sure what that way is for my particular situation.
Here is the code:
class PokedexSelector extends Component {
constructor(props) {
super(props);
this.state = {value: "National", pokedexes: []};
this.generatePokedexList();
this.handleChange = this.handleChange.bind(this);
this.generatePokedexList = this.generatePokedexList.bind(this);
this.pokedexList = this.pokedexList.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
generatePokedexList() {
const pokedexes = [];
fetch("https://pokeapi.co/api/v2/pokedex/")
.then(response => response.json())
.then(myJson => {
let results = myJson["results"];
results.forEach(function(pokedex) {
let pokedexName = pokedex["name"];
let pokedexLink = "https://pokeapi.co/api/v2/pokedex/" + pokedexName;
let pokedexDisplayName = capitalize(pokedexName.replace('-',' '));
pokedexes.push(
{
name: pokedexName,
displayName: pokedexDisplayName,
link: pokedexLink
}
);
});
this.state.pokedexes = pokedexes;
console.log(this.state.pokedexes)
})
}
pokedexList() {
if (this.state.pokedexes.length > 0) {
console.log("listing")
return (
this.state.pokedexes.map(pokedex => (
<option>{pokedex.displayName}</option>
))
)
}
}
render() {
return (
<select id="pokedex-selector" value={this.state.value} onChange={this.handleChange}>
{this.pokedexList()}
</select>
)
}
}
export default PokedexSelector;
I tried using componentDidMount() as below, but I'm not sure how to specifically target one component for changes in this case (the <select> element).
componentDidMount() {
{this.pokedexList()}
}
Any ideas? Thanks!
You should make your fetch calls before the render method is triggered, ideally in componentDidMount and store the response in the state. The component will re-render only when the state or props changes.
state should be updated via this.setState() method and should not be directly mutated using this.state.
In your case, since you're trying to mutate the state directly using this.state the component will not re-render. You should replace it with this.setState().
Try this code
class PokedexSelector extends Component {
constructor(props) {
super(props);
this.state = {value: "National", pokedexes: []};
this.handleChange = this.handleChange.bind(this);
this.generatePokedexList = this.generatePokedexList.bind(this);
this.pokedexList = this.pokedexList.bind(this);
}
componentDidMount() {
this.generatePokedexList();
}
handleChange(event) {
this.setState({value: event.target.value});
}
generatePokedexList() {
const pokedexes = [];
fetch("https://pokeapi.co/api/v2/pokedex/")
.then(response => response.json())
.then(myJson => {
let results = myJson["results"];
results.forEach(function(pokedex) {
let pokedexName = pokedex["name"];
let pokedexLink = "https://pokeapi.co/api/v2/pokedex/" + pokedexName;
let pokedexDisplayName = capitalize(pokedexName.replace('-',' '));
pokedexes.push(
{
name: pokedexName,
displayName: pokedexDisplayName,
link: pokedexLink
}
);
});
this.setState({pokedexes: pokedexes}); // use setState()
})
}
pokedexList() {
if (this.state.pokedexes.length > 0) {
console.log("listing")
return (
this.state.pokedexes.map(pokedex => (
<option>{pokedex.displayName}</option>
))
)
}
}
render() {
return (
<select id="pokedex-selector" value={this.state.value} onChange={this.handleChange}>
{this.pokedexList()}
</select>
)
}
}
export default PokedexSelector;
It should be this.setState and not this.state.pokedexes = pokedexes. Do not mutate state directly.
this.setState({
pokedexes
})

React - onChange function 'this.state' is undefined

I'm experimenting with React and I'm trying to create a Search to filter a list of items. I have two components, the main one displaying the list of items which calls the Search component.
I have an onChange function that sets the term in the state as the input value and then calls searchItems from the main component to filter the list of items. For some reason in searchItems, this.state is undefined. I thought adding bind to onInputChange in the Search component would sort it out but it did not make any difference. Maybe there's something I'm missing.
Main Component
import React, { Component } from 'react';
import _ from 'lodash';
import Search from './search';
class Items extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("[url].json")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
}
),
(error) => {
this.setState({
isLoaded: true,
error
})
}
}
searchItems(term) {
const { items } = this.state;
const filtered = _.filter(items, function(item) {
return item.Name.indexOf(term) > -1;
});
this.setState({ items: filtered });
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
}
else if (!isLoaded) {
return <div>Loading...</div>;
}
else {
return (
<div>
<Search onSearch={this.searchItems}/>
<ul>
{items.map(item => (
<li key={item.GameId}>
{item.Name}
</li>
))}
</ul>
</div>
)
}
}
}
export default Items;
Search Component
import React, { Component } from 'react';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
term: ''
};
}
render() {
return (
<div>
<input type="text" placeholder="Search" value={this.state.term} onChange={event => this.onInputChange(event.target.value)} />
</div>
);
}
onInputChange(term) {
this.setState({ term });
this.props.onSearch(term);
}
}
export default Search;
You didn't bind searchItems() in the Items component.
Try changing it to an arrow function:
searchItems = () => {
// blah
}
or otherwise binding it in the constructor():
constructor() {
// blah
this.searchItems = this.searchItems.bind(this);
}
or when you call it.
You can read more about this here.

updating set state in api call react

I'm having issues with setting this.setState from within my API call. If I console.log the stocks array inside the axios call the data is available in the array. It is not available outside if it.
Is the problem because this.setState is merging objects? I'm having a hard time conceptualizing what is happening here. How do I fix this problem so I can pass the contents to props?
import React, { Component } from 'react';
import axios from 'axios';
import SearchBar from './components/search_bar';
import StockList from './components/StockList';
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {
stocks: [],
term: null,
value: ''
};
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
value: e.target.value
});
}
handleClick(e) {
if(e) e.preventDefault();
this.setState({
value: '',
term: this.state.value
});
let term = this.state.value;
const key = 'F41ON15LGCFM4PR7';
const url = `https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=${term}&apikey=${key}`;
axios.get(axios.get(url)
.then(res => {
let stocks = Array.from(res.data['Stock Quotes']).map((stock) => [{symbol: stock['1. symbol'], price: stock['2. price'], volume: stock['3. volume'], timestamp: stock['4. timestamp']}]);
this.setState((state, props) => {
return [...this.state.stocks]
})
})
.catch(error => console.log(error))
)
}
render () {
let stocks = this.state.stocks;
const value = this.state.value;
return (
<div className="App">
<h1>Stock Search</h1>
<SearchBar value={ value }
onChange={ this.handleChange }
onClick={ this.handleClick }/>
<StockList stockItems={ stocks }/>
</div>
);
}
}
export default App;
Your setState there is the issue, it's messing up the structure of your state.
this.setState((state, props) => {
return [...this.state.stocks]
});
Should be either:
this.setState({
// set stocks to that array you parsed from the axios response
stocks
});
or
this.setState((state, props) => {
return {
...state,
// set stocks to that array you parsed from the axios response
stocks
};
});
I suggest that because you're accessing the stocks via this.state.stocks in your render

Categories