0
votes

I have used react hook here,ani I keep getting this error.

React Hook useEffect has a missing dependency: 'notes'. Either include it or remove the dependency array. You can also do a functional update 'setNotes(n => ...)' if you only need 'notes' in the 'setNotes' call react-hooks/exhaustive-deps

useEffect(() => {
    getNotes();
    const createNoteListner = API.graphql(
      graphqlOperation(onCreateNote)
    ).subscribe({
      next: noteData => {
        const newNote = noteData.value.data.onCreateNote;
        setNotes(prevNotes => {
          const oldnotes = prevNotes.filter(note => note.id !== newNote.id);
          const updatedNotes = [...oldnotes, newNote];
          return updatedNotes;
        });
        setNote("");
      }
    });
    const deleteNoteListner = API.graphql(
      graphqlOperation(onDeleteNote)
    ).subscribe({
      next: noteData => {
        const deleteNote = noteData.value.data.onDeleteNote;
        setNotes(prevNotes => {
          const updatedNotes = prevNotes.filter(
            note => note.id !== deleteNote.id
          );
          return updatedNotes;
        });
      }
    });
    const updateNoteListner = API.graphql(
      graphqlOperation(onUpdateNote)
    ).subscribe({
      next: noteData => {
        const updatedNote = noteData.value.data.onUpdateNote;
        setNotes(prevNotes => {
          const index = prevNotes.findIndex(note => note.id === updateNote.id);

          const updatedNotes = [
            ...notes.slice(0, index),
            updatedNote,
            ...notes.slice(index + 1)
          ];

          return updatedNotes;
        });
        setNote("");
        setId("");
      }
    });
    return () => {
      createNoteListner.unsubscribe();
      deleteNoteListner.unsubscribe();
      updateNoteListner.unsubscribe();
    };
  }, []);
2
in updateNoteListner you refers to notes instead of prevNotes. believe there is no special reason, just a typo - skyboyer

2 Answers

1
votes

In your code in the end of your code there is a }, [])

If you want your useEffect update by changing some props or state you can mention it in that array for example }, [props.sth]) and if you want your useEffect call every time you need to remove that empty array and your code will end like : })

-1
votes

You need to add notes in the dependencies of your effect If not , changes will not be reflected.

...

  return() =>{
      createNoteListner.unsubscribe();
      deleteNoteListner.unsubscribe();
      updateNoteListner.unsubscribe();
  }
}, [notes])