Jon Th
Jon Th

Reputation: 377

React - How to add local data to data from a REST api?

My react js page is fetching data from a REST service and it uses react-query to fetch and store it. The data is a list of objects.

I want to ADD one or two extra variables of my own to each object in this list that will only be on the react side and not go back to the REST server side.

Each object in the list will get an extra boolean variable expanded, which will indicate if this object should be expanded or not on the page.

How would you add such a variable to a list from the server? Would you modify the list itself and perhaps use immutability-helper? Or would you create a separate list of boolean flags and pointers to the other list?

Upvotes: 1

Views: 164

Answers (1)

JustRaman
JustRaman

Reputation: 1161

You can modify the list as if you don't send the data to the server after fetching it. This can be easily done with a spread operator.

const newList = oldarrOfObj.map(_o=>{
  return {..._o, expanded: true}
})

let suppose you have done some changes in the arr and you want to notify the server.

const oldList = newList.map(_o=>{
  delete _o.expanded
  return _o;
})

Upvotes: 2

Related Questions