search

Home  >  Q&A  >  body text

Dynamically setting state in React is invalid

I'm trying to dynamically set up an array and render it using useState hook. But it seems the array is not set. Here is my code:

import React, { useState, useEffect } from "react";

export default ({ item }) => {
    const [attachments, setAttachments] = useState([]);
    const setAttachmentValues = function(response){
        setAttachments(response.data);
        
    }
    const fetchMedia = async ()=> {
        setAttachments([]);           
        await apiCall().then((response) => {                
            setAttachmentValues(response);                
        });
    }
    
    useEffect(() => {
        fetchMedia();
    }, []);
    return (
        <>
           <div className="w-full">
                {(attachments.map((ele) => {
                      <div>{ele}</div>
                )} 
        </>
    )
}

apiCall() will return an array of objects.

In some cases, it is valid to set the state in this way. What's the actual issue here?

P粉366946380P粉366946380431 days ago409

reply all(1)I'll reply

  • P粉868586032

    P粉8685860322023-09-09 10:58:22

    So you can render the data

    import React, { useState, useEffect } from 'react';
    
    export default ({ item }) => {
      const [attachments, setAttachments] = useState([]);
    
      useEffect(() => {
        
        fetch('https://jsonplaceholder.typicode.com/users')
          .then((response) => response.json())
          .then((response) => {
            setAttachments(response);
            console.log(response);
          });
      }, []);
      return (
        <>
           <div>
            {attachments.map(item => <div key={item.username}> {item.username} </div> )}
          </div>
        </>
      );
    };

    reply
    0
  • Cancelreply