Home > Enterprise >  Set object in state from list
Set object in state from list

Time:01-29

I am working on a ToDo list in React where users can do CRUD operations. The last function I want to implement is updating a task.

Currently, you can load all items you already made. These items are visible in a list, each with an edit button to update the corresponding information.

Whenever a user clicks the update button, I want to load all the information in the input fields. These fields show in a pop-up menu after clicking the update button. However, I can not seem to get this to work. The input fields stay empty.

I have the following local state, no redux:

  const [formValue, setFormValue] = useState({
    title: "",
    category: "",
    description: "",
    priority: 1, //default is 1
  });

The function that is bound to the "edit" button: I also tried to set the setFormValue with the entire object but I could not get that to work either.

  function handleEditOpen(event) {
    for (const key in event) {
      const value = event[key];

      setFormValue({
        ...formValue,
        key: value,
      });
    }

    setEditDialogOpen(true);
  }

I did just learn about the async React state, hence console.log()'s don't show information instantly. However, with the for-loop in function, the state still didn't update.

One of the input fields (made with Material UI):

    <TextField
      required
      className="createItemCategoryTextfield"
      type="category"
      name="category"
      id="outlined-basic"
      variant="outlined"
      margin="normal"
      color="primary"
      label="Category"
      defaultValue={formValue.category}
      onChange={handleInputChange}
      focused
    />

How would I be able to load all information of a task in my local state, to show them in the edit screen and their corresponding input fields?

CodePudding user response:

Firstly update state only one by directly

 setFormValue((prevState)=>{
   ...prevState,
   ...event,
 });

instead of setting defaultValue directly set value

CodePudding user response:

I dont see the value property in your material ui element - TextField value properties, for example

 const [name, setName] = useState([])

  cosnt handleChangeValue = (someValue) => {
      setName(someValue)
  }

     <TextField
     value={name}
     onChange={(e) => handleChangeValue(e.target.value}
     />
  • Related