Rick & morty API REACT
Solution 1:
I can't tell what your Requests.getEpisode
function does, but if you are using axios
like your tags suggest, you could do something like this:
const getEpisode = (item) => {
axios.get(item[0]).then((res)=>{
return res.data.name
})
.catch((err)=>{
console.log(err)
})
}
Depending on what your Requests.getEpisode()
function looks like, you might just need to update the getEpisode
function that you have in your post to return res.data.name
instead of res.name
Update:
Based on the new code OP has shared, I don't think there are any issues with how the request is made. I think the issue is that getEpisode(item.episode)
doesn't return anything. To solve this, you could try updating a state variable after your episode is retrieved from the api. Something like this:
import React from "react";
import axios from "axios";
const getEpisode = (item) => {
return _getEpisode(item[0])
.then((res) => {
return res.name;
})
.catch((err) => {
console.log(err);
});
};
const _getEpisode = async (URL) => {
const { data: res } = await axios.get(`${URL}`);
return res;
};
export default function App() {
const [episode, setEpisode] = React.useState("");
React.useEffect(() => {
getEpisode(["https://rickandmortyapi.com/api/episode/10"]).then((res) => {
setEpisode(res);
});
});
return <h5>{"Episode: " + episode}</h5>;
}
The api data is retrieved in the useEffect
hook, and then state is updated so that the episode title displays in your component. You can see it working in this sandbox