Anvin
Anvin

Reputation: 49

loosing old data when updating the array in zustand

export const useSocketDataStore = create((set) => ({
  socketConnection: {},
  setSocketConnection: (connection) => set({ socketConnection: connection }),
  latestBidsFromSocket: [],
  setLatestBidsFromSocket: (bids) => set({ latestBidsFromSocket: bids }),
}));



    import { useSocketDataStore } from './store';

    export const useUpdateSocketDataStore = () => {
      const { latestBidsFromSocket, setLatestBidsFromSocket } =
        useSocketDataStore();
      const updateLatestBidsSocket = (data) => {
        setLatestBidsFromSocket([data].concat(latestBidsFromSocket));
      };
      return { updateLatestBidsSocket };
    };

i use this custom hook to update the zustand store. but i loose old data in latestBidsFromSocket when i try to concat new value into it.

Upvotes: 0

Views: 1702

Answers (2)

Anvin
Anvin

Reputation: 49

I got the issue fixed. It was because of the closure. The value of the latestBidsFromSocket passed to the updateLatestBidsSocket function remain same in every function call of updateLatestBidsSocket.

I corrected the code like below.

import { useEffect, useState } from 'react';
import { useSocketDataStore } from './store';

export const useUpdateSocketDataStore = () => {
  const { latestBidsFromSocket, setLatestBidsFromSocket } =
    useSocketDataStore();
  const [latestBidSocketData, setLatestBidSocketData] = useState({});

  useEffect(() => {
    if (Object.keys(latestBidSocketData).length) {
      setLatestBidsFromSocket(
        [latestBidSocketData].concat(latestBidsFromSocket)
      );
    }
  }, [latestBidSocketData]);

  return { setLatestBidSocketData };
};

Upvotes: 1

lithion
lithion

Reputation: 119

How about: [...data, ...latestBidsFromSocket] I never had a problem with joining arrays this way.

Upvotes: 0

Related Questions