0

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}
        </>
    )
}```

1 Answer 1

2

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: ""}]);
Sign up to request clarification or add additional context in comments.

4 Comments

still giving me the same error.. maybe its something with the api because every other api I have is rendering just fine with an empty array and a simple fetch call
you can check if the api sends an empty array or not.
I figured it out I set my state to undefined and instead of mapping over the array I just returned my state
I'm happy for you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.