trying to delete from an atom yields Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement

  Kiến thức lập trình

i am trying to build a workout and the user will add an exercise in which case they will be redirected to another page where they can select an exercise and input the number of desired sets and reps. This has no issue and works smoothly. however when i try to delete an exercise i am facing difficulty

this is the build page:

"use client";
import React from 'react';
import { useAtom } from 'jotai';
import { viewAtom } from '../../../utility/viewAtom'; // Import the view atom
import WorkoutBuilderContent from '../../components/build/WorkoutBuilderContent';
import RoutineBuilderContent from '../../components/build/RoutineBuilderContent';

const WorkoutBuilder = () => {
  const [view, setView] = useAtom(viewAtom); // Use the view atom

  return (
    <div className="container mx-auto p-4">
      <div className="flex justify-center mb-4 space-x-4">
        <button
          onClick={() => setView('workout')}
          className={`px-4 py-2 font-semibold rounded ${view === 'workout' ? 'bg-blue-500 text-white' : 'bg-gray-300 text-gray-700'}`}
        >
          Build Workout
        </button>
        <button
          onClick={() => setView('routine')}
          className={`px-4 py-2 font-semibold rounded ${view === 'routine' ? 'bg-purple-500 text-white' : 'bg-gray-300 text-gray-700'}`}
        >
          Build Routine
        </button>
      </div>
      {view === 'workout' && <WorkoutBuilderContent setView={setView} />}
      {view === 'routine' && <RoutineBuilderContent />}
    </div>
  );
};

export default WorkoutBuilder;

which will utilize this component

import React, { useState, useEffect } from 'react';
import { useAtom } from 'jotai';
import { workoutAtom, getExerciseAtom, deleteExerciseAtom   } from '../../../utility/exerciseAtom';
import { useRouter } from 'next/navigation';
import { PlusIcon } from '@heroicons/react/24/solid';
import ExercisePanel from './ExercisePanel';
import { useAtomValue } from 'jotai';
import useResetAtoms from '../../../utility/useResetAtoms'; // Import the reset hook
import { profileIdAtom } from '../../../store';

const WorkoutBuilderContent = ({ setView }) => {
  const [workout, setWorkout] = useAtom(workoutAtom);
  const [exerciseIds, setExerciseIds] = useState(workout.exerciseIds); // Local state for exerciseIds
  const [loading, setLoading] = useState(false); // Loading state
  const router = useRouter();
  const resetAtoms = useResetAtoms(); // Get the reset function
  const [error, setError] = useState(null); // State for error message
  const [currentUser] = useAtom(profileIdAtom);
  const [isPublic, setIsPublic] = useState(workout.public);

  useEffect(() => {
    setExerciseIds(workout.exerciseIds);
  }, [workout.exerciseIds]);

  const exercisesDetails = exerciseIds.map(id => {
    const exerciseAtom = getExerciseAtom(id);
    return { ...useAtomValue(exerciseAtom), id }; // Ensure id is included
  });

  const handleAddExercise = () => {
    router.push('/build/exercises'); // Navigate to the exercises page
  };

  const handleDeleteExercise = (id) => {
    console.log(exerciseIds);
    console.log(id);
    var filtered = exerciseIds.filter((name) => name !== id);
    setExerciseIds(filtered);
    // Remove the corresponding atom from the exerciseAtoms map
    deleteExerciseAtom(id);
    //router.push('/home');
  };

  const renderedExercisePanels = exerciseIds.map((exerciseId) => (
    <ExercisePanel key={exerciseId} id={exerciseId} onDelete={handleDeleteExercise} />
  ));


  return (
    <div>
      <h2 className="text-2xl font-bold mb-4">Build Workout</h2>
      {error && (
        <div className="mb-4 p-4 text-sm text-red-700 bg-red-100 rounded-lg" role="alert">
          <span className="font-medium">Error:</span> {error}
        </div>
      )}
      <div className="mb-4">
        <label className="block text-sm font-medium text-gray-700 mb-2">Workout Name:</label>
        <input
          type="text"
          value={workout.name}
          onChange={(e) => setWorkout({ ...workout, name: e.target.value })}
          className="block w-full px-4 py-2 border rounded-md focus:outline-none focus:ring focus:border-blue-300"
        />
      </div>
      <div className="flex items-center mb-4">
        <label className="block text-sm font-medium text-gray-700 mr-2">Public:</label>
        <input
          type="checkbox"
          checked={isPublic}
          onChange={handleCheckboxChange}
          className="form-checkbox h-5 w-5 text-blue-600"
        />
      </div>
      <div className="flex justify-end mb-4">
        <button
          onClick={handleAddExercise}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 flex items-center"
        >
          <PlusIcon className="w-5 h-5 mr-2" />
          Add Exercise
        </button>
      </div>
      <div className="space-y-4">
        {renderedExercisePanels}
      </div>
      <div className="mt-4">
        <button
          onClick={handleSaveWorkout}
          className="w-full px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
        >
          Save Workout
        </button>
      </div>
    </div>
  );
};

export default WorkoutBuilderContent;

Note: i removed some functions to reduce size of code

and this uses this panel component

import React from 'react';
import { useAtom } from 'jotai';
import { getExerciseAtom } from '../../../utility/exerciseAtom';

const ExercisePanel = ({ id, onDelete }) => {
  const [exercise] = useAtom(getExerciseAtom(id));

  const getImage = (id) => {
    // Assuming the images are stored locally in the public/images directory
    // Replace this logic with the actual path to your images
    return `/exercises/${id}/0.jpg`;
  };

  return (
    <div className="flex items-center p-4 border rounded-md shadow-md bg-white mb-4">
      <img
        src={getImage(id)}
        alt={exercise.name}
        className="w-16 h-16 rounded mr-4"
      />
      <div className="ml-4 flex-grow">
        <h3 className="text-lg font-bold">{exercise.name}</h3>
        <p className="text-sm">{exercise.sets}x - {exercise.reps} reps</p>
      </div>
      <button
        onClick={() => onDelete(id)}
        className="text-red-500 hover:text-red-700"
      >
        Delete
      </button>
    </div>
  );
};

export default ExercisePanel;

This is how the exercise is being added to the atom on when the page has been redirected

    if (!workout.exerciseIds.includes(id)) {
      setWorkout((prevWorkout) => ({
        ...prevWorkout,
        exerciseIds: [...prevWorkout.exerciseIds, id],
      }));
    }

Note these are the atoms

import { atom } from 'jotai';

// Atom to store workout name, list of exercise IDs, and public/private status
export const workoutAtom = atom({
  name: '', // workout name
  exerciseIds: [], // generated ids
  public: false // public/private status
});

// Map to store exercise atoms
const exerciseAtoms = new Map();

export const getExerciseAtom = (id) => {
  if (!exerciseAtoms.has(id)) {
    exerciseAtoms.set(
      id,
      atom({
        id,
        name: '', // exercise name
        sets: 0,
        reps: 0
      })
    );
  }
  return exerciseAtoms.get(id);
};

getExerciseAtom.clearExerciseAtoms = () => {
  exerciseAtoms.clear();
};

// Function to delete an exercise atom
export const deleteExerciseAtom = (id) => {
  if (exerciseAtoms.has(id)) {
    exerciseAtoms.delete(id);
  }
};
import { atom } from 'jotai';

export const viewAtom = atom(''); // Default to neither choice

i have tried various things based on what i have seen for similar issues. the problem is i am a little unsure as to why this is ocurring so trying to fix it is a challenge.

LEAVE A COMMENT