Home > database >  Reactjs map function causing the whole page to go blank
Reactjs map function causing the whole page to go blank

Time:01-10

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.

CodePudding user response:

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;

CodePudding user response:

You need to pass the response you got and save it to your state using set function.

.then(response => setArticles(response.data.articles))
  • Related