Search code examples
javascriptreactjsapireact-hooksmap-function

How to map through and store an API response as an array of objects in state React JS


I am trying to map through a server side API response to store first three items in state as an array of objects with title and url key/value pairs. I am getting an "objects are not valid as React children" error when I run this code. How do I properly push objects to my articles useState array so that I can then map over the array to render them as links on my page? Thanks...

const CodeNews = () => {

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

    useEffect(() => {
        axios.get('http://localhost:8000/apiKey')
        .then((res)=>{
            console.log(res)
            let tempArr = [];
            for(let i=0;i < 3; i++){
                tempArr.push({
                    title: res.data.articles[i].title,
                    url: res.data.articles[i].url
                })
            }
            setArticles(tempArr);
        })
        .catch((err)=>console.log(err))
    },[])

Solution

  • Probably the solution will be to change the rendering method to something like this:

    articles.map((el) => (
      <a href={el.url}>{el.title}</a>
    ))
    

    This is because you can't render a whole object in JSX.