Reputation: 259
I would like to fetch a an api from the state which was returned from the reducer. This is my container: PokeDetailApi.js
import React, {Component} from "react";
import {connect} from "react-redux";
import axios from "axios";
class PokeDetailApi extends Component{
constructor(){
super();
this.state = {
pokedetails:""
}
}
componentDidMount(){
axios.get({this.props.pokemon.url}).then( (obj) => {
this.setState({
pokedetails: obj.data.results
});
});
}
render(){
if(!this.props.pokemon){
return (
<div>
<h1>Please select a pokemon.</h1>
</div>
)
}
// const url = this.props.pokemon.url;
const urlapi = this.state.pokedetails;
console.log(url);
console.log(urlapi);
return(
<div>
<p>{this.props.pokemon.name}</p>
</div>
)
}
}
function mapStateToProps(state){
return {
pokemon: state.selected_pokemon
}
}
export default connect(mapStateToProps)(PokeDetailApi);
{this.props.pokemon.url} returns a url of a specific pokemon. I want to display all the details of that pokemon using that url which is found here: https://pokeapi.co/
This is the returned object from the reducer:
{
name:"bulbasaur"
url:"http://pokeapi.co/api/v2/pokemon/1/"
}
What is the correct way of accessing the objects from an api from a reducer using axios?
Upvotes: 0
Views: 483
Reputation: 66355
You are talking about reducers, but calling fetch directly in your component.. you should be calling an action which does the fetching.
Anyway aside from this you can perform another fetch in your .then using the result of the first fetch (pokedetails), not in your render:
axios.get(this.props.pokemon.url)
.then(res => res.data.results)
.then(axios.get) // fetch on pokedetails
.then(console.log) // console.log result, here you could setState results
Upvotes: 1