1

I want to update array in the product "table" via PUT request. lets say users array (product has many users)

localhost:1337/api/products/2

i am sending data in body

{
  "data": {
    "users": [4,6,8] //i want to push here next user but in json it is impossible [...users, newUser]
  }
}

the problem is that my previous values which was in the arrray are lost when i use put becouse this is how PUT works.

Why i need it? I use strapi and there relation is made via array. I just need to update array. But i dont know how to do this.

Maybe should i to use redux and push value to array in store and then update??

1

1 Answer 1

1

You can update your values with the use of the spread operator.

a = {
  "data": {
    "users": [4,6,8]
  }
}

UpdatedValues = {
    ...a, data: {
        ...a.data, users:
            [...a.data.users, 'newValues']
    }
}
console.log(UpdatedValues);

You can update your array prior and send that as a value to your API request.

oldArray = [1, 2, 3];
newArray = [...oldArray, "newValue"];

requestPayload = {
  data: {
    users: newArray,
  },
};

console.log(requestPayload)

2
  • Do u mean that i should do GET request first, receive data, modify and then make a PUT request??
    – SimonZ89
    Commented Apr 21, 2022 at 18:28
  • If you already have the data then you don't need to make an API call.
    – mc-user
    Commented Apr 22, 2022 at 3:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.