ked00
ked00

Reputation: 1

getting undefined is not a function when trying to .map an api in react

im trying to make a call to an api everything works fine until I try to map over it to render elements on the screen. im using thenewsapi.com I keep getting TypeError: undefined is not a function (near '...newStory.map...').


export default function News() {
    const [newStory, setNewStory] = React.useState([]);



    React.useEffect(() => {
       const fetchArticle = async () =>{
        const requestOptions = {
            method: 'GET'
        };
        
        const params = {
            api_token: 'api_key',
            categories: 'business,tech,sports',
            language: "en",
            limit: '1'
        };
        
        const esc = encodeURIComponent;
        const query = Object.keys(params)
            .map(function(k) {return esc(k) + '=' + esc(params[k]);})
            .join('&');
        
        await fetch("https://api.thenewsapi.com/v1/news/all?" + query, requestOptions)
          .then(response => response.text())
          .then(result => setNewStory(result))
          .catch(error => console.log('error', error));
       }
       fetchArticle()
    }, [])

    console.log(newStory);

    const newArticle = newStory.map(({ title}, index) => {
        return <h5 key={index}>{title}</h5>
    })
   

    return (
        <>
           {newArticle}
        </>
    )
}```

Upvotes: 0

Views: 218

Answers (1)

Ali Navidi
Ali Navidi

Reputation: 1035

Its because newStory is an empty array at first and it takes time to fetch data from api you can use an if for your render like this:

 return (
        <>
           {newStory && newStory.map(({ title}, index) => {
        return <h5 key={index}>{title}</h5>
    })}
        </>
    )

or define an empty title for your useState like this:

const [newStory, setNewStory] = React.useState([{title: ""}]);

Upvotes: 2

Related Questions