fetch()在JavaScript中 – 向JSON服务器添加新对象

huangapple go评论78阅读模式
英文:

fetch() in js - adding new object to json server

问题

我有一个关于向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": []
}

有人可以帮忙吗?

英文:

I've a question about adding new object to json server:

I have a calendar and after every change of date, I want to add this date on server. Right now it looks like this:

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

and code:

  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);
    }
  };

At the beginning I have current day from the context. But after every day change, the newDay is replacing a day and I want it to be added, ex.:

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

Anyone?

答案1

得分: 1

以下是代码的翻译部分:

SOLUTION需要创建新对象映射新日期数组并填充对象

const { day, userObject, newDay, addNewDay, tasks } = useContext(UserContext);

// 包含今天日期和任务的对象
let obj = { dates: [{ [day]: tasks }] };

const [date, setDate] = useState(new Date());
const onChange = date => {
  setDate(date);
  addNewDay([...newDay, date.toLocaleDateString()]);

  // 将新日期添加到对象中
  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);
  }
};
英文:

SOLUTION (had to create new object, map newDay array and fill the object)

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);
    }
  };

huangapple
  • 本文由 发表于 2020年1月6日 17:20:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定