V
V
Vann Damm2020-11-29 19:43:09
React
Vann Damm, 2020-11-29 19:43:09

Why does useDispatch write other data to the store when it fires for the first time in useEffect?

There is a useAction hook, which is used in the hock, and on the first render, it writes to the store not the data that was expected. You have to hardcode the condition for the preloader.
useAction hook:

export const useAction = (action, data, deps = null) => {
  const dispatch = useDispatch();
  useEffect(
    () => {
      dispatch(action({...data})) 
    },
    deps ? [data.url, ...deps] : [data.url,dispatch]
  );
};

HOC in which it is used:
export const withTasks = (WrappComponent) => {
  return (props) => {
    const location = useLocation();
    const token = useStore().getState().auth.login.token;
        useAction(getAllTasks, { url: location.pathname , headers:{Authorization: `Bearer ${token}`}},);
    const tasks = useSelector((state) => state.tasks.tasksArr);
       if(!tasks[0] || !tasks){
         return(
         <div>Preload</div>
       )
      }
     return <WrappComponent {...props} tasks={tasks} />;
  };
};

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question