Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.6 kB
4
Indexable
Never
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import Spinner from "../components/Spinner";
import { getWorkouts, reset } from "../features/workouts/workoutSlice";
import WorkoutItem from "../components/WorkoutItem";
import WorkoutForm from "../components/WorkoutForm";
import { AppDispatch, RootState } from "../app/store";
function Dashboard() {
  const navigate = useNavigate();
  const dispatch: AppDispatch = useDispatch();
  const { user } = useSelector((state: RootState) => state.auth);
  const { workouts, isLoading, isError, message } = useSelector(
    (state: RootState) => state.workouts
  );
  useEffect(() => {
    if (isError) {
      console.log(message);
    }
  }, [isError, message]);
  useEffect(() => {
    if (!user) {
      navigate("/login");
    }
    dispatch(getWorkouts());
    return () => {
      dispatch(reset());
    };
  }, [user, navigate, dispatch]);

  if (isLoading) {
    return <Spinner />;
  }
  return (
    <>
      <section className="heading">
        <h1>Welcome {user && user.name}</h1>
        <p>workouts Dashboard</p>
      </section>
      <WorkoutForm />

      <section className="content">
        {workouts.length > 0 ? (
          <div className="workouts">
            {workouts.map((workout) => {
              return <WorkoutItem key={workout._id} workout={workout} />;
            })}
          </div>
        ) : (
          <h3> You have not set any workouts.</h3>
        )}
      </section>
    </>
  );
}

export default Dashboard;