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!
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.
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...
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) .
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 [].
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With