JS中的fetch() - 向JSON服务器添加新对象



我有一个关于向 json 服务器添加新对象的问题:

我有一个日历,每次更改日期后,我想在服务器上添加此日期。现在它看起来像这样:

[
{
"name": "three",
"dates": {
"6.01.2020": []
},
"id": 3
},
{
"name": "four",
"dates": {
"5.01.2020": []
},
"id": 4
}
]

和代码:

const { day, changeDay, userObject, newDay, addNewDay, tasks } = useContext(
UserContext
);
const [date, setDate] = useState(new Date());
const onChange = date => {
setDate(date);
// changeDay(date.toLocaleDateString());
addNewDay(date.toLocaleDateString());
try {
fetch(`http://localhost:3003/users/${userObject.id}`, {
method: 'PATCH',
body: JSON.stringify({ dates: { [newDay]: [] } }),
headers: {
'Content-Type': 'application/json'
}
});
} catch (err) {
console.error(err);
}
};

一开始,我从上下文中得到了今天。但是在每天更改之后,newDay 正在替换一天,我希望添加它,例如:

"dates": {
"6.01.2020": [],
"7.01.2020": [],
"8.01.2020": [],
}

任何人?

解决方案(必须创建新对象,映射newDay数组并填充对象(

const { day, userObject, newDay, addNewDay, tasks } = useContext(UserContext);
// object with today date and tasks
let obj = { dates: [{ [day]: tasks }] };
const [date, setDate] = useState(new Date());
const onChange = date => {
setDate(date);
addNewDay([...newDay, date.toLocaleDateString()]);
// Add new days to the object
newDay.map((el, i) => {
obj.dates.push({ [newDay[i]]: [] });
});
try {
fetch(`http://localhost:3003/users/${userObject.id}`, {
method: 'PATCH',
body: JSON.stringify({ dates: obj.dates }),
headers: {
'Content-Type': 'application/json'
}
});
} catch (err) {
console.error(err);
}
};

相关内容

  • 没有找到相关文章

最新更新