React State in the course details page is setting values wrongly but the logged values after creating the course is correct

30 views Asked by At

So I have a form that is used to create a course/attendance:

<form onSubmit={handleSubmit} className="w-full mt-[65px] flex flex-col gap-[30px]">
                        <div className="flex flex-wrap flex-col gap-[40px]">
                            <FormField 
                                labelName="Course Code *" 
                                placeholder="Enter the course code"
                                inputType="text"
                                value={form.courseCode}
                                handleChange={(e) => handleFormFieldChange('courseCode', e)}
                            />
                            <FormField 
                                labelName="Course Name"
                                placeholder="Provide the title of the Attendance"
                                inputType="text"
                                value={form.courseName}
                                handleChange={(e) => handleFormFieldChange('courseName', e)}
                            />
                            <FormField 
                                labelName="Lecturer"
                                placeholder="Provide lecturer's name"
                                inputType="text"
                                value={form.lecturer}
                                handleChange={(e) => handleFormFieldChange('lecturer', e)}
                            />
                            <FormField 
                                labelName="Attendance Description *"
                                placeholder="Provide a description of the Attendance"
                                isTextArea
                                value={form.description}
                                handleChange={(e) => handleFormFieldChange('description', e)}
                            />
                            <label className="font-epilogue font-medium text-[16px] text-white" htmlFor="department">Department *</label>
                                <select
                                    id="department"
                                    className="w-[300px] p-[8px] rounded-[5px] bg-[#3a3a43] text-white"
                                    value={form.department}
                                    onChange={(e) => handleFormFieldChange('department', e)}
                                >
                                    <option value="" disabled>Select Department</option>
                                    {departmentOptions.map((option) => (
                                        <option key={option} value={option}>
                                            {option}
                                        </option>
                                    ))}
                                </select>
                                <label className="font-epilogue font-medium text-[16px] text-white" htmlFor="department">Program Level *</label>
                                <select
                                    id="programLevel"
                                    className="w-[300px] p-[8px] rounded-[5px] bg-[#3a3a43] text-white"
                                    value={form.programLevel}
                                    onChange={(e) => handleFormFieldChange('programLevel', e)}
                                >
                                    <option value="" disabled>Select Program Level</option>
                                    {programOptions.map((option) => (
                                        <option key={option} value={option}>
                                            {option}
                                        </option>
                                    ))}
                                </select>

The handleFormFieldChange will then set the form using react state:

const[ form, setForm ] = useState({
        courseCode: '',
        lecturer: '',
        courseName:'',
        description:'',
        department:'',
        programLevel:'',
    });

const handleFormFieldChange =(fieldName, e) =>{
        let value = e.target.value;
        if (fieldName === 'courseName') {
            value = value.replace(/\//g, ''); 
        }
        setForm(({ ...form, [fieldName]: value }));
        console.log({ ...form, [fieldName]: value });
    }

Then call the createCourse from AttendanceContext:

import   { useStateContext } from '../../context/AttendanceContext.jsx';

const { createCourse } = useStateContext();

const handleSubmit = async (e) => {
        e.preventDefault();
        try{
            setIsLoading(true);
            console.log({...form});
            await createCourse({...form});
            setIsLoading(false);
            //navigate('/attendance');
        } catch (error) {
            console.error("There was an error creating the course", error);
        }
    }

In AttendanceContext, createCourse would communicate with the solidity code. When I console.log the form after creating the course in the blockchain the console.log has the right values

const createCourse = async (form) => {
      const provider = new ethers.providers.Web3Provider(ethereum);
      const contract = new ethers.Contract(contractAddress, contractABI, provider);
      const address = window.ethereum.selectedAddress 
      try {
        if (!address) {
          await connect();
        }
    
        const signer = provider.getSigner();
        const contractWithSigner = contract.connect(signer);
        const data = await contractWithSigner.createCourse(
          form.courseCode,
          form.lecturer,
          form.courseName,
          form.description, 
          form.department,
          form.programLevel
          //startTime,
          //endTime,
        );
        console.log(form);
        console.log('Contract call success', data);

      } catch (error) {
        console.error('Contract call failure', error);
      }
    };

But when I open up the course details here:

import React, {useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import user from '../../images/user.png';
import { CountBox, CustomButton, Loading, Navbar, Footer } from '../../components/index.js';
import { useStateContext } from '../../context/AttendanceContext.jsx';
//import { daysLeft, convert } from '../../utils';
import AdminChecker from '../../utils/adminChecker.js';

const AdminCloseAttendanceDetails = () => {

    const { state } = useLocation();
    const navigate = useNavigate();
    const { contract, address, closeCourse, getAttendees, getAttendeesCount, getLecturer } = useStateContext(); 
    const [ isLoading, setIsLoading ] = useState(false);
    const [ lecturer, setLecturer ] = useState('');
    //const[amount, setAmount]= useState('');
    const [ attendees, setAttendees ] = useState([]);
    const [ currentAttendeeCount, setCurrentAttendeeCount ] = useState([]);
    //const remainingTime = convert(state.endTime);
    const [ isLoadingAttendees, setIsLoadingAttendees ] = useState(true);
    

    const fetchAttendees = async () => {
      setIsLoadingAttendees(true);
      try{
        const lecturer = await getLecturer(state.pId);
        const data = await getAttendees(state.pId);
        console.log("State before setting lecturer:", state);
      console.log("Lecturer fetched:", lecturer);
        setAttendees(data);
        setLecturer(lecturer);
        const attendeeCount = await getAttendeesCount(state.pId);
        setCurrentAttendeeCount(attendeeCount);
      } finally {
        setIsLoadingAttendees(false);
      }
    }

The logs are giving me field entries in different fields and the programLevel field is just gone. the image field was should also be removed since I no longer use it but is still in the state

The console log after creating the course

The console log of the created the course at the details page

The expected outcome should be this:

The console log after creating the course

But instead I am getting this:

The console log of the created the course at the details page

Since the form is passed and used to create the course in the blockchain and I do get the logs of what I sent, why does it log wrongly in the details? And this results in me not being able to use the fields.

0

There are 0 answers