I have a state subscriptions
that is an array of objects. When I get a websocket message I grab symbol
and price
. With these I want to setSubscriptions
and either edit the matching object if symbol === name
or if it doesn't exist, add it. I figured out how edit price if it exists, but how can I add a new entry to the array if it doesn't?
const [subscriptions, setSubscriptions] = useState([{name: 'xbtusd', price: ''}])
const updateSubscription = (symbol, price) => {
setSubscriptions((prevSubscriptions) =>
prevSubscriptions.map((instrument) =>
instrument.name === symbol
? { ...instrument, price: price }
: instrument
)
)
}