Search code examples
reactjsreduxreact-hooksredux-toolkit

How to update redux slice?


I have a problem, I can't update the user's gold with this code. I'd like to update the user's gold from his current gold to current gold + 100 every 10 seconds.

This code doesn't work, I think I misunderstood something but can't figure out what! I'd like the gold to be dispatched when I leave the page. I mean I have my current gold shown in the header for example and in the page I can see every 10 secs from 0 my gold updated ... once I leave the page in the header I'd like to have my current gold + the gold earn.

useEffect in my component:

const [chrono, setChrono] = useState<number>(0);
const user: any = useSelector((state: any) => state.user);
const dispatch = useDispatch();
const [gold, setGold] = useState(0);

useEffect(() => {
  const updateGold = setInterval(() => {
    setGold((gold) => gold + 100);
  }, 10000);

  return () => {
    dispatch(
      userSlice.actions.update({
        ...user,
        gold: user.gold + gold,
      })
    );
    clearInterval(updateGold);
  };
}, []);

reducer

update: (state: any, { payload }) => {
  console.log("action =>", payload);
  return {
    ...state,
    ...payload,
  };
},

Solution

  • I think it makes more sense and would be simpler to dispatch the an update action on the interval instead of updating local state and synchronizing state later.

    Example:

    const dispatch = useDispatch();
    
    useEffect(() => {
      const updateGold = setInterval(() => {
        dispatch(
          userSlice.actions.addGold(100);
        );
      }, 10000);
    
      return () => {
        clearInterval(updateGold);
      };
    }, []);
    

    Slice

    addGold: (state: any, { payload }) => {
      state.gold = state.gold + payload;
    },