简体   繁体   中英

REACT: Can't set useState to an array of objects. Console log shows undefined

I am using react and a mongoose/mongo database. On the page loading, I do an API call and receive an array of objects (they are "posts" with titles, descriptions, etc). I am trying to map over the data to dynamically display the post info on separate cards. I can get the data from the API call, but when I try to change state to the array of objects and console log it, I get undefined.

Attached is the photo of the code and result:

Console log of Info

The code of API call (related to pic 1 - please notice the code line numbers)

Why isn't usestate accepting the change in state from the data? Attached is my code:

import React, { useState, useEffect } from 'react'
import API from "../utils/API"


const Home = () => {

    const [PostObject, setPosts] = useState({
        title: "",
        description: "",
        image: ""
    })

    const [PostList, setList] = useState()


    useEffect(() => {
        retrievePosts()
    }, [])


    const handleInputChange = (e) => {
        e.preventDefault()
        setPosts({ ...PostObject, [e.target.name]: e.target.value })
    }


    const createPost = (e) => {
        e.preventDefault()
        setPosts({ ...PostObject, title: "", description: "", image: "" })
        API.addPost(PostObject)
            .then(retrievePosts())
    }


    const retrievePosts = () => {
        API.getPost()
            .then(res => {
                console.log(res.data);
                setList(res.data)
                console.log(PostList);
            })
    }

Why isn't usestate accepting the change in state from the data? Attached is my code:

Because you attached an empty dependency array to useEffect as in:

useEffect(() => {
        retrievePosts()
    }, [])

If you pass an empty dependency array, this useEffect will be called only once. If you want to run the useEffect after every data change you have to pass the data to the dependency array:

useEffect(() => {
            retrievePosts()
        }, [data /*i.e PostList*/])

However, be careful not to re-render the component infinite amount of times. You can check libraries like React-Query and SWR

One more thing:

I can get the data from the API call, but when I try to change state to the array of objects and console log it, I get undefined.

setState is an async call. You can't log the data right after calling setData . Take a look at this article or to this question and see if they help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM