Dynamically setting state in React is invalid
P粉366946380
P粉366946380 2023-09-08 17:35:50
0
1
433

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粉366946380
P粉366946380

reply all(1)
P粉868586032

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>
    </>
  );
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template