state does not update on second click of button

Viewed 24

I my app i have an array of buttons which works as an sidemenu. If i click the same button in the menu two times it crashes because the state of "value" does not update second time and a loop there is on the page does not have anything to loop then.

I have this function handleOnChangeNavBar. It works fine when there is no files where input_type is array. I can change between pages and it will set the state of "value" to ("") each time a new button is choosen. But if it contains the input_type "array" i only work the first time clicking and the second time it crashes. The error is saying that "value" does not contain anything when trying to map through - but why does it then contain the right data on first click but not second click?

  function handleOnChangeNavBar(title) {
    console.log(title)
    Object.keys(files).forEach((key) => {
      if (files[key].title === title) {
        setData(files[key]);
        setInput(files[key].Input);
        setValue("")
        {
          Object.values(files[key].Input).map((form) => {
            if (form.input_type === "array") {
              if (!(Object.keys(value).includes(form.name))) {
                setValue({ ...value, [form.name]: [""] })
              }
            }
          }
          )
        }
      }
    });
    console.log(value)
    setChoice(title);
    setSchema("");
  };

Here i have the functionality of creating the list menu

<h1>Service Requests</h1>
            {Object.keys(files).map((key) => (
              <button className={`list-item${choice === files[key].title ? ' selected' : ''}`} class="list-item" value={files[key].title} key={files[key].title} onClick={() => handleOnChangeNavBar(files[key].title)}>
                {files[key].title}</button>
            ))}
          </div>
        </div>
        <div class='double-column'>
          {ContentVisible && (
          ...
          )}

0 Answers
Related