简体   繁体   中英

How to update an object that is within an array

How can I put data into object values in an array in javaScript? I am taking data from the backend using axios and useEffect hook! taking data I need to push that data into an object which is inside of the array! code I wrote doesn't work and ignorant! there is a JS question!

const Articles = () => {


 const [articleData, setArticleData] = useState([]);

 useEffect(() => {
    const fetchBlogs = async () => {
      try {
        const res = await axios.get(
          `${process.env.REACT_APP_API_URL}/article/list/all`
        );
        setArticleData(res.data);
      } catch (err) {}
    };
    fetchBlogs();
  }, []);


  for (let article in articleData) {
   
      data: [
        {
          key: article._id,
          title: article.title,
          author_username: article.author_username,
          category: article.category_name,
          subcategory: article.subCategory_name,
          publication_date: article.publication,
        },
      ],
   
  }


return (
  <div className='articles'>
     <Table
        columns={columns}
        dataSource={data}
        size='large'
      />
  </div>

)

};

You can use map to get a new array, then save it to the state and use the state variable in JSX. Something like this should work for you

const Articles = () => {


 const [articleData, setArticleData] = useState([]);

 useEffect(() => {
    const fetchBlogs = async () => {
      try {
        const res = await axios.get(
          `${process.env.REACT_APP_API_URL}/article/list/all`
        );
        setArticleData(res.data.map(article => ({
          key: article._id,
          title: article.title,
          author_username: article.author_username,
          category: article.category_name,
          subcategory: article.subCategory_name,
          publication_date: article.publication,
        })));
      } catch (err) {}
    };
    fetchBlogs();
  }, []);


return (
  <div className='articles'>
     <Table
        columns={columns}
        dataSource={articleData}
        size='large'
      />
  </div>

)

};

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