Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set dynamic key in state via useState React hooks

Tags:

reactjs

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!

like image 666
akshay Avatar asked Jun 03 '19 07:06

akshay


People also ask

How do you set a state with a dynamic key name?

Output: Open your browser. It will by default open a tab with localhost running and you can see the output shown in the image. Fill in the required details and click on the button. As you can see in the output new state with a dynamic name is created with the value you entered.

How do you create a dynamic state in React JS Hooks?

Defining state const Form = ({ formData }) => { const [page, setPage] = useState(0); const [currentPageData, setCurrentPageData] = useState(formData[page]); const onSubmit = e => { e. preventDefault(); // todo - send data somewhere }; return ( <form onSubmit={onSubmit}> <p>todo...

How do I change state using useState hook?

To update the state, call the state updater function with the new state setState(newState) . Alternatively, if you need to update the state based on the previous state, supply a callback function setState(prevState => newState) .


1 Answers

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 [].
    })
}
like image 160
Chris Ngo Avatar answered Oct 17 '22 06:10

Chris Ngo