React Native - News API

This lesson is part of a series on React Native.

Step 11 - News API Calls

Make sure you've gone through the news-api-samples.html sample code before starting this.

Start by overhauling the news home screen (app/news/index.js) to look like this (note that I basically copied code from the main homepage and tweaked it):

import { StyleSheet, Text, View } from 'react-native'
import { useRouter } from 'expo-router' 
import CustomScreen from '../../components/CustomScreen'
import CustomButton from '../../components/CustomButton'
import {Ionicons} from '@expo/vector-icons'
import Spacer from '../../components/Spacer'
import {Colors} from '../../Theme'

const Home = () => {

  const router = useRouter()

  return (
    <CustomScreen>
      <Ionicons size={150} name="newspaper-outline" color={Colors.secondary}/>
      <Spacer height={35} />
      <View style={{width:'80%'}}>
        <CustomButton onPress={() => router.replace('/news/sports')}>
          <Text style={{color: 'white', textAlign: 'center', fontWeight: 'bold'}}>Sports</Text>
        </CustomButton>
        <Spacer height={20} />
        <CustomButton onPress={() => router.replace('/news/weather')}>
          <Text style={{color: 'white', textAlign: 'center', fontWeight: 'bold'}}>Weather</Text>
        </CustomButton>
      </View>
    </CustomScreen>
  )
}

export default Home

const styles = StyleSheet.create({})

Check it out in the browser (or on your device)

Create an .env file (if you dont' already have one) in the project folder (this file will be ignored from the repo - look at the .gitignore file) Add your API key like so:

EXPO_PUBLIC_NEWS_API_KEY="PUT YOUR KEY HERE"

NOTE: You should prefix your env variables with EXPO_PUBLIC_

Install Axios (if you have not yet installed it for the project):

npm install axios

Create an api folder in the project root (if you have not already created it)

Create a file named news-api.js file into the api folder and add this code to the file:

import axios from "axios";

const BASE_URL="https://newsapi.org/v2/everything";

export async function getNews(topic) {
  try {
    const response = await axios.get(BASE_URL, {
      params: {
        q: topic,
        apiKey: process.env.EXPO_PUBLIC_NEWS_API_KEY,
        pageSize: 10
      }
    });
    console.log(response.data);
    return response.data.articles
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

Now update sports.jsx to look like this:

import { StyleSheet, Text, View } from 'react-native'
import { useEffect, useState } from 'react'
import { getNews } from '../../api/news-api'
import CustomView from '../../components/CustomScreen'
import Spacer from '../../components/Spacer'

const Sports = () => {

  const [articles, setArticles] = useState([])

  useEffect(() => {
    // Fetch sports news articles
    getNews('sports').then((sportsArticles) => {
      setArticles(sportsArticles)
    })
  }, [])

  return (  
    <CustomView style={{padding: 20}}>
      {articles.map((article, index) => (
        <View key={index}>
          <Text style={{width: '100%',textAlign: 'left'}}>{article.title}</Text>
          <Spacer height={10} />
        </View>
      ))}
    </CustomView>
  )
}

export default Sports

const styles = StyleSheet.create({})