обновить массив в mockAPI - PullRequest
       3

обновить массив в mockAPI

0 голосов
/ 27 марта 2020

У меня есть такой объект на mockAPI

{
   "id": "1",
   "name": "qqq",
   "email": "qqq",
   "password": "qqq",
   "tasks": [],
   "gettingTasks": [],
}

И я хочу добавить в массив "tasks" несколько "ids"

const createTaskUser = (id, idTask) => {
const user = usersGateway.fetchUser(id)   here i query the user and get the object as above
const newUser = {
    ...user,
     tasks:idTask
    }
usersGateway.updateUser(id, newUser) is a function that accepts a user id that needs to be updated and a new dataset
}

Если я запускаю эту функцию это перезапишет значения, но мне нужно добавить данные.
После нескольких вызовов массив должен выглядеть следующим образом:

{
   "id": "1",
   "name": "qqq",
   "email": "qqq",
   "password": "qqq",
   "tasks": [1,4,75,3,2],
   "gettingTasks": [],
}

1 Ответ

0 голосов
/ 28 марта 2020

Вы можете добавить sh в массив или использовать оператор распространения. шаг проверки tasks: [...user.tasks, idTask]

const createTaskUser = (id, idTask) => {
  const user = usersGateway.fetchUser(id); // here i query the user and get the object as above
  const newUser = {
    ...user,
    tasks: [...user.tasks, idTask]
  };
  usersGateway.updateUser(id, newUser); //is a function that accepts a user id that needs to be updated and a new dataset
};

// Если разрешено pu sh

const createTaskUser = (id, idTask) => {
  const user = usersGateway.fetchUser(id); // here i query the user and get the object as above
  user.tasks.push(idTask)
  usersGateway.updateUser(id, user); //is a function that accepts a user id that needs to be updated and a new dataset
};
...