I am new to react and have read the react docs on how to make an Ajax call. They made it look so simple when they were returning the json information but it doesn't work for me. I am trying to call the json information and set it to this.state.stockSymbol but every time I try to access the information I use typeof and it returns an object. I can see the json information clearly when I console.log it but for some reason it won't update in my getSymbol function. I think it has to to with the async call but I'm not totally understanding it. Can someone point me in the right direction?
Here is my code:
class Stocks extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: '',
stockSymbol: [],
isLoaded: false
}
}
typeSymbol = (e) => {
this.setState({
userInput: e.target.value.toUpperCase()
}, (e) => {
console.log(this.state.userInput)
})
}
getSymbol = (e) => {
e.preventDefault(),
this.setState({
stockSymbol: this.state.stockSymbol
}, () => {
console.log(typeof this.state.stockSymbol)
console.log(this.state.stockSymbol)
})
}
componentDidMount() {
fetch(`https://finnhub.io/api/v1/stock/symbol?exchange=US&token=${key}`)
.then(res => res.json())
.then(
(results) => {
this.setState({
isLoaded: true,
stockSymbol: results
});
console.log(results)
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { stockSymbol, userInput, results } = this.state
stockSymbol.map((stock, i) => {
if (userInput === this.state.stockSymbol) {
return (
console.log('same'),
{stock.displaySymbol}
);
}
})
return (
Введите символ акции {this.state.userInput} Отправить )}} ReactDOM.render ( , document.getElementById ('root'))