2

I have a form in React JS with some data that will have dynamic keys so I don't want to hardcode their assignment in setData. (Context: I want the form to contain these values when the form loads)

Basically, I have a map which maps all of my keys to their values. I am trying to do something along the lines of:

// Keys and values held here. 
 myMap = Map<string, mixed>;
 
 const [data, setData] = useState(() => {
    const data = {
      submit: 0,
      // Set data that I know the keys of here.
    };
    // Set data that I don't know the keys of here.
    // I am trying to dynamically set data[key] as follows (which does not work):
    Object.keys(myMap).forEach(key => data[key] = myMap[key]);
    return data;
  });

Anyone know why this is not working / how I can accomplish this?

FΣynman
  • 67
  • 1
  • 7
  • Is myMap a `props` coming from the parent? – Joshua Oct 30 '20 at 21:30
  • @konekoya yes, myMap is passed via props – FΣynman Oct 30 '20 at 21:31
  • 1
    Is it a value obtained by an async operation like an HTTP get or something? If so, you will need to use `useEffect` to wait until the async value is loaded and update the state then – Joshua Oct 30 '20 at 21:35
  • @konekoya no, I don't believe there are any issues in terms of that - I tried printing out the map on the line right before I try to set the values and it contains all of the info I expect it to – FΣynman Oct 30 '20 at 21:52
  • Okay, could you also include some data of that `myMap` variable? – Joshua Oct 30 '20 at 21:55
  • @konekoya Yep here's a sample: [age: 20, language: "english", user: null, ...] – FΣynman Oct 30 '20 at 22:01
  • And you don't want to just accomplish this initial state setting in a component did mount (i.e. `useEffect( () => { do it here }, [] )`)? – Seth Lutske Oct 30 '20 at 22:44
  • Can you expand your example to include where the `Map` is created/updated and how it is being passed down? For one thing, that looks like an incorrect initalisation of `myMap` since it is usually called as `new Map()` - you can also call `myMap.keys()` directly. As a general note, it is usually a [bad idea to use Maps with React](https://stackoverflow.com/questions/53605759/react-setting-state-to-an-es6-map/53606339#53606339). – lawrence-witt Oct 30 '20 at 23:57

0 Answers0