Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reactjs map function causing the whole page to go blank

im putting both my back and front end together and after i fetched my data with Effect Hook i mapped the data and retuned the article title in an h2 tag ,and the map function causes the whole page to go blank ,but when i comment out that part the page seems to work just fine.

import './App.css';
import {useState, useEffect} from "react";



function App() {

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

useEffect(()=>{
    fetch('http://127.0.0.1:8000/api/articles',{
        'method':'GET',
        headers: {
            'content-Type':'application/json',
            'Authorization':'Token a9714c85387c802207740a7bd8882f4a748733be',
        }
    })
    .then(response => response.json())
    .then(response => setArticles())
    .catch(error => console.log(error))
},[])

  return (
    <div className="App">

        <h3> Django & Reactjs Blog App</h3>

        {articles.map(article =>{
            return <h2> {article.title} </h2>

        })}

    </div>
  );
}

export default App;

I expected the page to load just as normal but with an article with dummy title.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Missed to set state for article and blank page was caused due to using a map function on empty array. Please consider checking browser console for errors.

import './App.css';
import { useState, useEffect } from "react";



function App() {

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

    useEffect(() => {
        fetch('http://127.0.0.1:8000/api/articles', {
            'method': 'GET',
            headers: {
                'content-Type': 'application/json',
                'Authorization': 'Token a9714c85387c802207740a7bd8882f4a748733be',
            }
        })
            .then(response => response.json())
            // Missed setting state for articles
            .then(response => setArticles(response))
            .catch(error => console.log(error))
    }, [])

    return (
        <div className="App">

            <h3> Django & Reactjs Blog App</h3>
            {/** make sure articles are not null */}
            {articles.length && articles.map(article => {
                return <h2> {article.title} </h2>

            })}

        </div>
    );
}

export default App;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading