YASH KUMAR
YASH KUMAR

Reputation: 35

How do I print titles from the given api?

function News() {

const[stories, setStories] = useState([]);


useEffect(() => {

    const getStoriesData = async () => {
        await fetch("https://hn.algolia.com/api/v1/search_by_date?tags=(story,poll)")
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
            const stories = Object.keys(data).map((story) => (
                {   
                    
                    title: story.title,
                    url: story.url,
                    points: story.points,
                }
            ));

            setStories(stories);
        });
    }

    getStoriesData();
}, []);


return(
    <div className="news">
        {stories.map((story) => (
            <p>{story.title}</p>
        ))}
        <h1>this is news</h1>
    </div>
    
)
}

export default News;

I want to print the title from each data but it doesn't show anything. Previously I thought it is because my data is in object so I used Object.keys(data) but I still didn't get answer.

Upvotes: 0

Views: 156

Answers (1)

mplungjan
mplungjan

Reputation: 178350

You need to map the data.hits

fetch("https://hn.algolia.com/api/v1/search_by_date?tags=(story,poll)")
  .then(response => response.json())
  .then(data => { 
    const stories = data.hits.map(({title,url,points}) => ({title,url,points}))
    console.log(stories)
  });

Upvotes: 1

Related Questions