akshay
akshay

Reputation: 1161

Set dynamic key in state via useState React hooks

I want to set dynamic state with dynamic key by uuid in it in functional component Below is example with the class based Component in React

class App extends Component {
  state = {
    [uuid()]: []
  };

How can achieve this with functional component ?

const App = props=>{
 const [list, setList] = useState([uuid()]);

I tried using above approach it gives me output

["4b4c8872-0c35-49a6-a98b-ef7abcb2cef8"]

but desired is ["4b4c8872-0c35-49a6-a98b-ef7abcb2cef8": []]

Thanks in Advance!

Upvotes: 11

Views: 15161

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

You need to pass in an object instead of an array to useState

const App = props=>{
 const [list, setList] = useState({ [uuid()] : [] });

If you want to append new keys to the state value, you can do the following.

addList = (e) => {
    setList({
      ...list,  //take existing key-value pairs and use them in our new state,
      [uuid()]: []   //define new key-value pair with new uuid and [].
    })
}

Upvotes: 19

Related Questions