Hello!
Today I was trying to optimize my code, but i’m actually stuck because i cant use function from another file.
What i’ve done so far, is that I created a folder ''component", and inside, created a file name " Api.js "
Here’s the code:
import React, {Component} from 'react';
import axios from 'axios';
class Api extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
summonername: '',
token: "Tokenmagic",
id: '',
champions: [],
champion:[],
name: [],
golds: [],
SortGold:[],
MvpGolds: [],
};
this.GetMaxValue = this.GetMaxValue.bind(this);
this.apiSummoner = this.apiSummoner.bind(this);
this.apiAccount = this.apiAccount.bind(this);
this.apiGame = this.apiGame.bind(this);
this.onClick = this.onClick.bind(this);
}
async apiSummoner() { // Get summonner information
let summonername = this.state.summonername;
const summonerurl = `/summoner/v4/summoners/by-name/${summonername}`;
await axios.get(summonerurl, { //Attendre le résultat de la promesse d'axios
params: {}, headers: {
'X-Riot-Token': this.state.token
},
})
.then(res => {
console.log(res);
this.setState({summonersname: res.data.name});
this.setState({summonerslevel: res.data.summonerLevel});
this.setState({summonersid: res.data.accountId});
})
.catch(error => {
console.log("An error occured on apiSummoner D: ", error);
});
};
async apiAccount() { // get Last matchId of the summoner
let summonerId = this.state.summonersid;
const matchurl = `/match/v4/matchlists/by-account/${summonerId}`;
await axios.get(matchurl, {
params: {},
headers: {'X-Riot-Token': this.state.token}
})
.then(res => {
console.log(res);
this.setState({matchId: res.data.matches[0].gameId});
this.setState({matchchampion: res.data.matches[0].champion});
this.setState({matchlane: res.data.matches[0].lane})
})
.catch(error => {
console.log("An error occured on apiAccount D: ", error)
})
}
async apiGame() {
let matchID = this.state.matchId;
const gameurl = `/match/v4/matches/${matchID}`;
await axios.get(gameurl, {
params: {},
headers: {'X-Riot-Token': this.state.token}
})
.then(res => {
for (let i = 0; i < 10; i++) {
this.setState({
name:
[...this.state.name, res.data.participantIdentities[i].player.summonerName]
});
this.setState({
golds:
[...this.state.golds, res.data.participants[i].stats.goldEarned]
});
this.setState({
champion:
[...this.state.champion,
getChampionById(this.state.champions, res.data.participants[i].championId)]
});
}
this.setState({bluetowerdestroy: res.data.teams[0].towerKills});
this.setState({redtowerdestroy: res.data.teams[1].towerKills});
this.setState({bluedragonkilled: res.data.teams[0].dragonKills});
this.setState({reddragonkilled: res.data.teams[1].dragonKills});
})
.catch(error => {
console.log("An error occured on apiGame D: ", error)
})
}
GetMaxValue() {
let Mvp = Math.max.apply(Math, this.state.golds);
for (let i = 0; i < 10; i++) {
if (Mvp === this.state.golds[i])
this.setState({MvpGolds: [...this.state.MvpGolds, this.state.golds[i] + "-> MVP"]});
else
this.setState({MvpGolds: [...this.state.MvpGolds, this.state.golds[i]]});
}
}
componentDidMount() {
fetch('http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json')
.then(response => response.json())
.then(res => {
this.setState({champions: res.data});
})
}
async onClick() {
try {
await Api.this.apiSummoner();
} catch (e) {
console.log("error : ", e)
}
try {
await this.apiAccount()
} catch (e) {
console.log("error", e)
}
try {
await this.apiGame()
} catch (e) {
console.log("error", e)
}
this.GetMaxValue()
}
}
function getChampionById (data, id) {
let dataKeys = Object.keys(data);
for (let key of dataKeys) {
if (data[key].key == id ) {
return data[key].name;
}
}
return {error: "Champion not found"}
}
export default Api;
And, thanks to those value get from the api, I use them is my app.js and render them.:
import React, {Component} from 'react';
import axios from 'axios';
import { Bar } from 'react-chartjs-2';
import Api from './components/Api.js';
class App extends Component {
render() {
const data = {
labels: [this.state.name[0], this.state.name[1], this.state.name[2], this.state.name[3], this.state.name[4],
this.state.name[5], this.state.name[6], this.state.name[7], this.state.name[8], this.state.name[9]],
datasets: [
{
label: 'Gold',
backgroundColor: 'rgb(255,215,0)',
borderColor: 'rgb(255,215,0)',
data: [this.state.golds[0], this.state.golds[1], this.state.golds[2],
this.state.golds[3], this.state.golds[4], this.state.golds[5], this.state.golds[6],
this.state.golds[7], this.state.golds[8], this.state.golds[9]],
}
]
};
return (
<div>
<label className={"label"}>
<input type="text" onChange={this.updateInput}/>
<input type="submit" onClick={Api.onClick} value="Search"/>
</label>
<h1>Summoner Information</h1>
<div> Name : {this.state.summonersname} </div>
<br/>
<div> Level : {this.state.summonerslevel} </div>
<br/>
<h1> Last Match : </h1>
<br/>
<h2> Blue Side </h2>
<h4> Summoners: </h4>
<div> : {this.state.name[0]} -> {this.state.champion[0]} -> {this.state.MvpGolds[0]} Golds </div>
<div> : {this.state.name[1]} -> {this.state.champion[1]} -> {this.state.MvpGolds[1]} Golds </div>
<div> : {this.state.name[2]} -> {this.state.champion[2]} -> {this.state.MvpGolds[2]} Golds </div>
<div> : {this.state.name[3]} -> {this.state.champion[3]} -> {this.state.MvpGolds[3]} Golds </div>
<div> : {this.state.name[4]} -> {this.state.champion[4]} -> {this.state.MvpGolds[4]} Golds </div>
<h4> Stats : </h4>
<div> : Dragon killed: {this.state.bluedragonkilled} </div>
<div> : Tower Destroid: {this.state.bluetowerdestroy} </div>
<br/>
<h2> Red Side </h2>
<h4> Summoners: </h4>
<div> : {this.state.name[5]} -> {this.state.champion[5]} -> {this.state.MvpGolds[5]} Golds</div>
<div> : {this.state.name[6]} -> {this.state.champion[6]} -> {this.state.MvpGolds[6]} Golds</div>
<div> : {this.state.name[7]} -> {this.state.champion[7]} -> {this.state.MvpGolds[7]} Golds</div>
<div> : {this.state.name[8]} -> {this.state.champion[8]} -> {this.state.MvpGolds[8]} Golds</div>
<div> : {this.state.name[9]} -> {this.state.champion[9]} -> {this.state.MvpGolds[9]} Golds </div>
<h4> Stats : </h4>
<div> : Dragon killed: {this.state.reddragonkilled} </div>
<div> : Tower Destroid: {this.state.redtowerdestroy} </div>
<div>
<h2>Game Gold</h2>
<Bar ref="chart" data={data} />
</div>
<br/>
</div>
);
}
}
export default App;
So I tried to follow mutiples things like : https://create-react-app.dev/docs/importing-a-component/ or https://www.youtube.com/watch?v=iWcNI4PIjVU, but react return me for example Cannot read property 'name' of null
, from this.state.name[0]
because he dont know what data it is.
Any help would be very appreciated, thanks !