0

I am trying to understand why this code would not work:

 const [data, setData] = useState(() => {
    var data = {
      some_var: 0,
    };
    data["test"] = "test";
    return data;
  });

I get the following error: Cannot assign "test" to data["test"] because property test is missing in object literal

but according to this post this is something I should be able to validly do in JS.

cosmicluna
  • 539
  • 1
  • 5
  • 16

1 Answers1

0

I tried this and it worked

import React, { useState } from "react";
import ReactDOM from "react-dom";
const App = () => {
  const [data, setData] = useState(() => {
    var data = {
      some_var: 0,
    };
    data["test"] = "test";
    return data;
  
  });
  console.log(data)====>{some_var: 0, test: "test"}

  return (
    <div >
     
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
zahra zamani
  • 1,323
  • 10
  • 27