Home > OS >  loosing old data when updating the array in zustand
loosing old data when updating the array in zustand

Time:06-12

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.

CodePudding user response:

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

CodePudding user response:

i got the issue fixed. it was because of the closure. the vlaue 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 };
};

  • Related