Tengo una matriz en mi db.json. Y puedo agregar un nuevo objeto. Pero cada vez que vuelvo a cargar la página, los datos se restablecen al estado predeterminado. ¿Cómo puedo almacenar datos de tal manera que se escriban en db.json y se muestren al recargar?
Mi db.json:
{"item": [ { "text": "Пошел в свой первый класс", "id": 0, "data": { "year": 2012, "day": 25, "month": 1 } }, { "text": "Поехал на чемпионат по бейсболу", "id": 1, "data": { "year": 2018, "day": 14, "month": 3 } }, { "text": "Поступил в институт", "id": 2, "data": { "year": 2007, "day": 12, "month": 4 } } ]}Mi estado:
const [value, setValue] = useState(''); const [valueYear, setValueYear] = useState(''); const [valueDate, setValueDate] = useState(''); const [valueMonth, setValueMonth] = useState(''); const [table, setTable] = useState([]); useEffect(() => { axios.get("http://localhost:3004/item").then(({ data }) => { setTable(data); })}, [])Mi función de agregar:
const addTask = (value, valueYear, valueDate, valueMonth) => { if (value) { const newItem = { id: table.length, text: value, data: { year: valueYear, day: valueDate, month: valueMonth, }, } setTable([...table, newItem]); }}Para escribir un archivo en Javascript necesitas usar NodeJS. En este caso, le aconsejo que use localStorage . Cuando establezca el nuevo estado de la tabla, coloque el siguiente código:
setTable([...table, newItem]); localStorage.setItem('table', [...table, newItem]);Y capturarlo en el estado inicial, así:
const [table, setTable] = useState(localStorage.getItem('table') || []); const addTask = (value, valueYear, valueDate, valueMonth) => { if (value) { const newItem = { id: table.length, text: value, data: { year: valueYear, day: valueDate, month: valueMonth, }, } axios.post('http://localhost:3004/item', newItem).then(() => { setTable([...table, newItem]); }) }}