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);
})
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…