user1357015
user1357015

Reputation: 11686

ReactJS performing a shallow copy on an object in one step

I am trying to copy the object I have in a component up to a property. I am able to get it to work like this:

 onSubmit: values => {

      data.label = values.label;
      data.userName = values.userName;
      data.recipientUserName = values.recipientUserName
      data.vanityURL = values.vanityURL;
      data.dollarAmount = values.dollarAmount;
      data.textData = values.textData;

I'm new to javascript but this feels very ugly. Is there a way I can do a direct shallow copy without iterating through every field?

The data object is created is passed in at the top as:

export default memo(({ id, data, isConnectable,setElements, removeElements}) => {

  const [show, setShow] = useState(false);
  const handleClose = (e) => {setShow(false)};
  const handleShow = () => setShow(true);

  
  const formik = useFormik({
    initialValues: {
      label: data.label,
      userName: '',
      recipientUserName: '',
      vanityURL: '',
      dollarAmount: '',
      textData: ''
    },
    onSubmit: values => {

      data.label = values.label;
      data.userName = values.userName;
      data.recipientUserName = values.recipientUserName
      data.vanityURL = values.vanityURL;
      data.dollarAmount = values.dollarAmount;
      data.textData = values.textData;
    },
    onReset: (values, { resetForm }) => resetForm(),
  });

return ( ....

The onSubmit is part of a Formik form.

Upvotes: 1

Views: 1427

Answers (2)

Eduard
Eduard

Reputation: 1374

In order to perform shallow copy, you can follow one of these methods.

  1. Use the spread (...) syntax
  2. Use the Object.assign() method
  3. Use the JSON.stringify() and JSON.parse() methods

Example 1

data = {...values}

Example 2

data = Object.assign({}, values)

Example 3

data = JSON.parse(JSON.stringify(values));

Upvotes: 1

Vishnu Sajeev
Vishnu Sajeev

Reputation: 974

You can do

const data = {...value}

Upvotes: 0

Related Questions