skip to Main Content

I am trying to retrieve article data from my backend api using a fetch request and display it on screen. The request retrieves the data successfully, however when I try to update the state of the component variables using the setArticle hook, nothing happens and the request completes without passing any data in.


function Home(props) {

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

    useEffect(() => {       
        fetch(`http://localhost:8000/api/articles/`, {
            method: 'GET',
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                console.log('Error:', result.error);
                return false;
            }
            console.log(result);
            setArticles(result);
            console.log(articles);
        })
    }, [])

    const articleList = articles.map((article) =>
        <ArticleCard article={article} width='400'/>
    )

    return(
        <ul className="article-list">
            {articleList}
        </ul>
    )
}

export default Home;

I’ve already read the React documentation at https://react.dev/reference/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value and hooks are still incredibly confusing. I understand that the state does not update, but this example takes place outside of a fetch request so the new variable is stored. How am I supposed to get the articles variable to update or return the new variable so that I can map the json data to the articleList?

2

Answers


    import "./styles.css";
    import { useState, useEffect } from "react";
    function Home() {
      const [articles, setArticles] = useState([]);
    
      const FetchArticle = async () => {
        await fetch(`https://jsonplaceholder.typicode.com/posts`)
          .then((response) => response.json())
          .then((result) => {
            if (result.error) {
              console.log("Error:", result.error);
              return false;
            }
            console.log(result);
            setArticles(result);
            // console.log(articles);
          });
      };
    
      useEffect(() => {
        FetchArticle();
      }, []);
    
      return (
        // return page HTML and articleList
        <>
          {articles.map((article) => (
            <h1>{article.title}</h1>
          ))}
        </>
      );
    }
    
    export default Home;

    Try this , your code is working fine. I used dummy data and the data can be easily rendered on the screen.

    Login or Signup to reply.
  1. It would be much better if you’ll use redux with redux-thunk here.

    redux is a smart-storage, redux-thunk is middleware for making requests like that fetch you have.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search