agobago
agobago

Reputation: 91

How to update only one property of an object?

I'm working on a not taking app. Each time you add a note, you get an empty text area component that you can edit (write some text) and the date when the note was added. I'm trying to update only the text of the note, so the user can edit, but I'm getting an error from TypeScript: "Argument of type 'string' is not assignable to parameter of type 'INote'".

export const App = () => {

  const [notesList, setNotesList] = React.useState<Array<INote>>([{text: '', date: new Date()}]);

  const updateNote = React.useCallback(
    (idx: number, text: string) => {
      const newList = [...notesList];
      newList.splice(idx, 1, text); 
      setNotesList(newList);
    },
    [notesList]
  );

Here's the list of my notes.

     {notesList.length > 0 &&
          (filteredNotes && filteredNotes.length > 0 ? (
            filteredNotes.map((note: INote, idx: number) => (
              <>
              <Note
                onChange={updateNote}
                remove={deleteNote}
                idx={idx}
                date={note.date}
                text={note.text}
                key={idx}
              />
              </>
            ))
          ) : (
            <Text>No results found</Text>
          ))}

Upvotes: 1

Views: 1088

Answers (1)

Bernhard Josephus
Bernhard Josephus

Reputation: 715

You get the error because you are trying to replace the item at the index of idx with a string, while your array is an array of INote. So, you need to pass the new INote object with the updated text as the code below.

const updateNote = React.useCallback(
    (idx: number, text: string) => {
      const newList = [...notesList];
      const newNote = { ...newList[idx], text } // this is the updated note
      newList.splice(idx, 1, newNote);  // pass the note here
      setNotesList(newList);
    },
    [notesList]
);

Or maybe directly change the text property

const updateNote = React.useCallback(
    (idx: number, text: string) => {
      const newList = [...notesList];
      newList[idx].text = text
      setNotesList(newList);
    },
    [notesList]
);

Upvotes: 2

Related Questions