I'm trying to fetch the json data using axios. Could you please tell me what am i doing wrong here
I have tried doing it using hooks as well but to no avail. i have put it below the class based component please have a look at it. Could you please tell me what am i doing wrong here
API : https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API_KEY
API_ KEY : 3055f8f90fa44bbe8bda05385a20690a
import React, { Component } from "react";
import axios from "axios";
import Post from "../../Component/Post/Post";
export default class Home extends Component {
state = {
posts: [],
};
componentDidMount() {
axios
.get(
"https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API_KEY",
{
headers: {
" API_KEY ": "3055f8f90fa44bbe8bda05385a20690a",
},
}
)
.then((response) => {
console.log(response.data);
this.setState({ posts: response.data });
})
.catch((err) => {
console.log("API call error:", err.message);
});
}
render() {
const posts = this.state.posts.map((post) => {
return <Post key={post.id} />;
});
return <div>{posts}</div>;
}
}
import React, { useState, useEffect } from "react";
import Post from "../../Components/Post/Post";
import axios from "axios";
const HomePage = () => {
const [posts, setPosts] = useState("");
let config = { Authorization: "3055f8f90fa44bbe8bda05385a20690a" }; //3055f8f90fa44bbe8bda05385a20690a
const url =
"https://newsapi.org/v2/top-headlines?sources=bbc-news&apiKey=API_KEY";
useEffect(() => {
AllPosts();
}, []);
const AllPosts = () => {
axios
.get(`${url}`, { headers: config })
.then((response) => {
const allPosts = response.data;
setPosts(allPosts);
})
.catch((error) => console.error(`Error: ${error}`));
};
return (
<div>
<Post className="Posts" posts={posts} />
</div>
);
};
export default HomePage;