简体   繁体   中英

React.js: Uncaught TypeError: response.data.posts is not iterable

I'm creating an infinity stroll and when trying to add the new data into the state with the existing data Uncaught TypeError: response.data.posts is not iterable comes up

const [posts, setPosts] = useState([]) //my state

setPosts((prev) => [...prev, ...response.data.posts]);// the way i'm trying to add the data

my api structure

posts: {
    current_page: 1
    data: [{id: 1, title: "Nobis iste sed ullam deleniti quis excepturi 
            nemo.",…},…]
    first_page_url: "http://127.0.0.1:8000/api/front/all-posts?page=1"
    from: 1
    last_page: 15
    last_page_url: "http://127.0.0.1:8000/api/front/all-posts?page=15"
    links: [{url: null, label: "« Previous", active: false},…]
    next_page_url: "http://127.0.0.1:8000/api/front/all-posts?page=2"
    path: "http://127.0.0.1:8000/api/front/all-posts"
    per_page: 10
    prev_page_url: null
    to: 10
    total: 150
    success: true

}

It seems like posts are objects in your API structure and that's why you got iterable error. Did you try

setPosts((prev) => [...prev, ...response.data.posts.data]);

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