0
votes

I have a react application that connects to a socket and gets a list of data (initial data) from one of the channel

the issue appears while I got the list again when reconnecting or when I change the route (refresh is of course not a problem)

and then I got the list again and need to update the state again with all the list (I am doing that with REDUX)

My question i how can I check or prevent from update the state again . is there any subject that supports that? or i should check if the whole list exists in the reducer? is it also a good solution to set a state in redux that said "fetched:true" and then don't dispatch in that case

listen to the channel: (class that listen to socket server create an observable using rxjs)

   socketService.server.on('list', (res: any) => {
     console.dir(res);
     subject$.next(res)
   });

update the state in redux-thunk action:

   .subscribe(vall).... {
      disptach(list)....
   });

socketService only connect to the socket and return a socket

1
where are you doing the subscribe to the socket? why is it called again? - tudor.gergely
@tudor.gergely hi, it's not called again - the server.on in the rxjs class that listens to the socket . and the thunk function subscribe to this, updated my question - Tuz
Does the res have an unique identifier, such as an id ? If so, you could use distinctUntilChanged((prev, crt) => prev.id === crt.id) - Andrei Gătej
@AndreiGătej. no its an array of objects - Tuz

1 Answers

0
votes

If you only need the value from the socket initially you should not read from it after you receive it initially.

You can either unsubscribe and not listen for any more messages (after the first one) or you can only get process the first message with rxjs:

// you can check here a condition for res if you need to 
// (that it is not empty for example)
.pipe(first(res => res))

or

.pipe(take(1))

This will ensure you only read and dispatch for the first message you receive from that connection.