Мои заметки компонент не работает должным образомJavascript

Форум по Javascript
Ответить
Anonymous
 Мои заметки компонент не работает должным образом

Сообщение Anonymous »


, поэтому я делаю приложение для хранения нот и Техническая ошибка или глюк пришли там, где я могу отредактировать заметки, и ничего с этим ничего не делаю. Не могли бы вы мне помочь. Кроме того, коды также доступны на моем GitHub. Но вот краткая версия.import React, { useContext } from 'react';
import { useState, useEffect, useRef } from "react";
import AddNotes from './AddNotes';
import NoteItem from './NoteItem';
import { useNotes } from '../../hooks/NotesProvider';

const Notes = () => {
const context = useNotes();
const { notes, getNotes, editNote } = context;
useEffect(() => {
getNotes();
}, []);
const ref = useRef(null);
const refClose = useRef(null);
const [note, setNote] = useState({id: "", etitle: "", econtent: "", etag: ""});

const updateNote = (currentNote) => {
ref.current.click();
setNote({id: currentNote._id, etitle: currentNote.title, econtent: currentNote.content, etag:currentNote.tag});
}

const handleClick = (e) => {
editNote(note.id, note.etitle, note.econtent, note.etag);
refClose.current.click();
}

const onChange = (e) => {
setNote({...note, [e.target.value]:e.target.value});
}

return (



{note.title}

{
deleteNote(note._id);
}}
>
[i] className="far fa-edit mx ... content}

);
};

export default NoteItem;

< /code>
addnotes.jsx:
import React, { useContext } from "react";
import { useState, useEffect } from "react";
import { useNotes } from "../../hooks/NotesProvider";

const AddNotes = () => {
const context = useNotes();
const { addNote } = context;
const [note, setNotes] = useState({ title: "", content: "", tag: "" });

const handleClick = (e) => {
e.preventDefault();
addNote(note.title, note.content, note.content);
setNotes({ title: "", content: "", tag: "" });
};

const onChange = (e) => {
setNotes({ ...note, [e.target.value]: e.target.value });
};

return (




Title




Content




Tag




Submit



);
};

export default AddNotes;


hooks/notesprovider.js:
import { createContext, useContext, useState } from "react";

const NotesContext = createContext();

const NotesProvider = ({children}) => {
const notesInitial = [];
const [notes, setNotes] = useState(notesInitial);

const getNotes = async(data) => {
try{
const response = await fetch("http://localhost:5000/api/auth/register",{
method: "GET",
headers:{
"Authorization": `Bearer ${localStorage.getItem("site")}`,
},
body: JSON.stringify(data),
});
const res = await response.json();
if(res){
console.log(res);
setNotes(res.data);
return;
}
throw new Error(res.message);
}catch(err){
console.error(err);
}
};

const addNote = async(title, content, tag) => {
try{
const response = await fetch('http://localhost:5000/api/notes/create-note',{
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("site")}`,
},
body: JSON.stringify({title, content, tag})
});
const res = await response.json();
if(res){
setNotes(res.data);
return;
}
throw new Error(res.message);
}catch(err){
throw new Error(err.message);
}
}

const editNote = async(id, title, content, tag) => {
try{
const response = await fetch(`http://localhost:5000/api/notes/update-note/${id}`,{
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("site")}`,
},
body: JSON.stringify({ title, content, tag})
});
const json = await response.json();

let newNotes = JSON.parse(JSON.stringify(notes));
if (newNotes && newNotes.length) {
for (let index = 0; index < newNotes.length; index++) {
const element = newNotes[index];
if (element._id === id) {
newNotes[index].title = title;
newNotes[index].content = content;
newNotes[index].tag = tag;
break;
}
}
} else {
console.error('newNotes is not defined or is empty');
}
setNotes(newNotes);
}catch(err){
throw new Error(err.message);
}
}

const deleteNote = async(id) => {
try{
const response = await fetch(`http://localhost:5000/api/notes/delete-note/${id}`,{
method: "DELETE",
headers:{
"Authorization": `Bearer ${localStorage.getItem("site")}`,
}
});
const res = await response.json();
if(res){
const newNotes = notes.filter((note) => {return note._id !== id});
setNotes(newNotes);
}
}catch(err){
throw new Error(err.message);
}
}
return (

{children}

)
};

export default NotesProvider;

export const useNotes = () => {
return useContext(NotesContext);
};


Подробнее здесь: https://stackoverflow.com/questions/794 ... g-properly
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»