简体   繁体   中英

how to set useState data on an object

I'm trying to set an object with useState, however I only get in initial value, can anyone see what I'm doing wrong, the object in question is setWishlist,

const CenterModal = props => {
  const [modalData, setModalData] = useState({
    color: 'red',
    title: '',
    description: ''
  });

const onSubmit = e => {
    e.preventDefault();
    props.onHide();
    const wishlistData = {
      color: modalData.color,
      title: modalData.title,
      description: modalData.description,
    };

    //Pass the data to Wishlist component
    props.wishlistdata(wishlistData);
    console.log('wishlistData: ', wishlistData);
  };
 }

const Wishlist = props => {

    const [wishList, setWishList] = useState({
    color: 'red',
    title: '',
    description: ''
  });

  const onWishListDataReceived = wishListData => {
    setWishList({
      color: wishListData.color
      title: wishListData.title,
      description: wishListData.description,
    });
    console.log('wish list data is: ', wishList);
  };

return(    
   <CenterModal
      title="EDIT WISHLIST ITEM"
      show={modalShow}
      onHide={modalClose}
      wishlistdata={e => onWishListDataReceived(e)}
   />
 )
}

in the console.log I only get the initial state,

I think the issue is because whenever you invoke the function you are not passing in an object with correct information as an argument. it is trying to access properties on the place holder so the correct info has to be passed when invoked, or it will just be undefined. Also don't think you need the square brackets around the keys.

I figured it out, Just for future reference,

I had to use useEffects like the following

useEffect(() => {
    console.log('wishlistdata is: ', wishList);
  }, [wishList]);

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