Search code examples
reactjsreact-propsuse-state

React useState/setState Error: Not a function when multiple instances of compnent are on same page


Having a bit of trouble here with some useState hooks maybe you know how to get this working! Here is a quick synopsis of what I am trying to do...

I am making a LMS webpage that lets teachers design courses. Teachers can pick from a template and insert video/text/picture. They might pick a two column layout, or three column layout. They can mix and match the content types in the layouts. So potentially the teacher can pick a 3 column layout and put three videos in the template.

I need to make sure that the student watches every second of the video before moving on - and I am super close to getting this to work. So I store some state in the main course file (CourseDash.js) shown below. The useState hook I am having trouble with is const [ videosToWatch, setVidosToWatch ] = useState([]);.

Basically I am passing setVideosToWatch to my video components (also shown below). If a video appears in the template, the video component adds the url to the videosToWatch array. When a video finishes playing, I add the same information to watchedVideos in CourseDash.js. That way I can check to see which videos the student has watched and make sure they watch them before proceeding with the course.

It works fine and dandy when I render one(1) VideoContent component in the template. But when a teacher creates a course that has two different video components on one template... I get the error "setVideosToWatch is not a function". Why does it work when rendering one video component? Why not both? Thanks for your help Here is the code:

//CourseDash.js
import React, { useState, useEffect } from 'react';
import NavBar from '../Layout/NavBar';
import { useAuth0 } from '@auth0/auth0-react'
import Welcome from './Welcome'
import CourseContent from './CourseContent';
import { Button } from 'reactstrap'
import Finish from './Finish';

export default function CourseDash(props) {
    const [ currentPanel, setCurrentPanel ] = useState('Welcome')
    const { getAccessTokenSilently, user, logout } = useAuth0();
    const [ navigation, setNavigation ] = useState()
    const [ course, setCourse ] = useState({})
    const [ customerInfo, setCustomerInfo ] = useState({})
    const [ student, setStudent ] = useState({})
    const [ selectedModule, setSelectedModule ] = useState({})
    const [ clicked, setClicked ] = useState('')
    const [ grade, setGrade ] = useState([])
    const [ finalGrade, setFinalGrade ] = useState(0);
    const [ allowedModules, setAllowedModules ] = useState([]);
    const [ allowedNext, setAllowedNext ] = useState(true)
    const [videosToWatch, setVideosToWatch ] = useState([])
    const [ watchedVideos, setWatchedVideos ] = useState([])

    useEffect(() => {
        currentPanel !== 'Welcome' && setSelectedModule(course.modules.filter(mod => mod.id === currentPanel)[0])
        currentPanel !== 'Welcome' && currentPanel !== 'Finish' && setClicked(course.modules.filter(mod => mod.id === currentPanel)[0].title)
    }, [currentPanel])

    useEffect(() => {
        setAllowedNext(videosToWatch.every(vid => watchedVideos.includes(vid)))
    }, [ watchedVideos, videosToWatch ])

    const getCourseContent = async (_id) => {
        try {
            const token = await getAccessTokenSilently();
            const response = await fetch(`/api/GetSingleCourse/${_id}`, {
                method: 'GET',
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json; Charset=UTF-8"
                }
            })
            const responseData = await response.json()
            setCourse(responseData[0])
            let tempNav = []
            responseData[0].modules.forEach(mod => {
                let navItem = {
                    buttonLink: mod.id,
                    buttonAlt: mod.title,
                    buttonType: 'module',
                    buttonName: mod.title,
                }
                tempNav.push(navItem)
            })
            setNavigation(tempNav)
        } catch (error) {
            console.log(error)
        }
    }

    const getCustomerInfo = async () => {
        try {
            const token = await getAccessTokenSilently();
            const response = await fetch(`/api/GetACustomer_id/${course.customerId}`, {
                method: 'GET',
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json; Charset=UTF-8",
                },
            })
            const responseData = await response.json();
            setCustomerInfo(responseData[0])
        } catch (error) {
            console.log(error)
        }
    }

    const getStudentInfo = async () => {
        try {
            const token = await getAccessTokenSilently();
            const response = await fetch(`/api/GetStudentByEmail/${user.name}`, {
                method: 'GET',
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json; Charset=UTF-8",
                }
            })
            const responseData = await response.json();
            setStudent(responseData[0])
        } catch (error) {
            console.log(error)
        }
    }

    useEffect(() => {
        if(course.customerId){
            getCustomerInfo()
        }
        if(course.modules){
            let availablePoints = 0
            let quizes = {}
            course.modules.forEach(mod => {
                if(mod.moduleType === 'quiz'){
                    quizes[mod.id] = {}
                    mod.quizContent.forEach(q => {
                        availablePoints += 1
                        quizes[mod.id][q.id] = 'studentAnswer'
                    })
                }
            })
            quizes.pointTotal = availablePoints
            setGrade(quizes)
        }
    }, [course])

    useEffect(() => {
        if(props.match.params.id){
            getCourseContent(props.match.params.id)
        }
        getStudentInfo()
    }, [props.match.params.id])

    const display = (panel) => {
        setCurrentPanel(panel)
        setClicked(course.modules.filter(mod => mod.id === panel)[0].title)
    }

    if(!navigation){
        return <div>Loading...</div>
    }

    const nextModule = () => {
        currentPanel === 'Welcome' && setCurrentPanel(course.modules[0].id)
        let indexOfModule = course.modules.findIndex(mod => mod.id === currentPanel)
        currentPanel !== 'Welcome' && setCurrentPanel(course.modules[indexOfModule + 1].id)
    }

    const prevModule = () => {
        let indexOfModule = course.modules.findIndex(mod => mod.id === currentPanel)
        currentPanel !== 'Welcome' && indexOfModule !== 0 && (setCurrentPanel(course.modules[indexOfModule - 1].id))
    }

    const finishCourse = async () => {
        let total = 0
        course.modules.forEach(mod => {
            if(mod.moduleType === 'quiz'){
                mod.quizContent.forEach( ques => {
                    if(ques.answer === grade[mod.id][ques.id]){
                        total += 1
                    }
                })
            }
        })

        let fGrade = total/grade.pointTotal

        setFinalGrade(fGrade)

        try {
            const token = await getAccessTokenSilently();
            const response = await fetch(`/api/UpdateStudent/${student._id}`, {
                method: 'PUT',
                headers: {
                    Authorization: `Bearer ${token}`,
                    "Content-Type": "application/json; Charset=UTF-8",
                },
                body: JSON.stringify({grades: [...student.grades.filter(g => g.course !== course._id), {course: course._id, grade: fGrade}]})
            })
        } catch (error) {
            console.log(error)
        }

        setCurrentPanel('Finish')
    }

    const enableButtons = () => {
        let indexOfCurrModule = course.modules.findIndex(mod => mod.id === currentPanel)
        currentPanel === 'Welcome' && setAllowedModules(mods => [...mods, course.modules[0].title])
        currentPanel !== 'Welcome' && currentPanel !== 'Finish' && indexOfCurrModule !== course.modules.length -1 && setAllowedModules(mods => [...mods, course.modules[indexOfCurrModule + 1].title])
        indexOfCurrModule === course.modules.length - 1 && setAllowedModules([])
    }

    if(!student){
        return <div className='d-flex w-100 h-100 align-self-center justify-content-center text-light'><h4  style={{
            borderRadius: '10px',
            backgroundColor: '#0F1D44',
            padding: '2%'
        }}>It seems like you have not been assigned this course...</h4></div>
    }

    return (
        <div 
        style={{
            display: 'flex',
            flexDirection: 'row',
            width: '100%',
            maxWidth: '78%',
            zIndex: '10'
        }}>
            <NavBar newButtons={navigation} display={display} clicked={clicked} allowedModules={allowedModules} />
            <div className='w-100 h-100' >
                <div className='m-4'>
                    <h1 className='text-light'>Welcome to {course.courseTitle}!</h1>
                    <span className='text-light'>For {student.name} at {customerInfo.business}.</span>
                </div>
                {currentPanel === 'Welcome' && <Welcome nextModule={nextModule} currentPanel={currentPanel} course={course} customerInfo={customerInfo} student={student} enableButtons={enableButtons} /> }
                {currentPanel !== 'Welcome' && currentPanel !== 'Finish' && <CourseContent selectedModule={selectedModule} grade={grade} setGrade={setGrade} setAllowedNext={setAllowedNext} setVideosToWatch={setVideosToWatch} videosToWatch={videosToWatch} setWatchedVideos={setWatchedVideos} />}
                {currentPanel === 'Finish' && <Finish finalGrade={finalGrade} course={course} customerInfo={customerInfo} student={student} /> }
                <div className='w-100 m-4' style={{
                    display: currentPanel === 'Welcome' || currentPanel === 'Finish' ? 'none' : 'flex'
                }}>
                    <Button onClick={prevModule} color='primary' size='md' alt='previous module' className='m-2' style={{width: '97%'}} disabled={course.modules.findIndex(mod => mod.id === currentPanel) === 0 || currentPanel === 'Welcome'}>←</Button>
                    <Button onClick={() => {
                        enableButtons();
                        nextModule() 
                        }} color='primary' size='md' alt='next module'className='m-2' style={{width: '97%'}} disabled={course.modules.findIndex(mod => mod.id === currentPanel) === course.modules.length - 1 || !allowedNext}>→</Button>
                    <Button onClick={() => {
                        finishCourse()
                        enableButtons();
                        }} color='success' size='md' alt='next module' 
                        disabled={!allowedNext}
                        className='m-3' 
                        style={{width: '97%', display: currentPanel === course.modules[course.modules.length - 1].id ? 'block' : 'none'}} >Finish Course!</Button>
                </div>

            </div>
        </div>
    )
}

Here is my video content component where each video gets rendered.

    //VideoContent.js
    import React, { useEffect } from 'react'

export default function VideoContent(props) {
    const { content, setAllowedNext, setVideosToWatch, videosToWatch, setWatchedVideos } = props

    const checkVideoPlay = () => { 
        setVideosToWatch(vids => [...vids, content]);
        let video = document.getElementById(content);

        let timeStarted = -1;
        let timePlayed = 0;
        let duration = 0;

        const getDuration = () => {
            duration = video.duration;
            document.getElementById("duration").appendChild(new Text(Math.round(duration)+""));
            console.log("Duration: ", duration);
          }

        // If video metadata is laoded get duration
        if(video.readyState > 0){
            getDuration.call(video);
        }
        else{
            //If metadata not loaded, use event to get it
            video.addEventListener('loadedmetadata', getDuration);
        }
        // remember time user started the video
        const videoStartedPlaying = () => {
          timeStarted = new Date().getTime()/1000;
        }
        const videoStoppedPlaying = (event) => {
          // Start time less then zero means stop event was fired vidout start event
          if(timeStarted>0) {
            var playedFor = new Date().getTime()/1000 - timeStarted;
            timeStarted = -1;
            // add the new number of seconds played
            timePlayed+=playedFor;
          }
          document.getElementById("played").innerHTML = Math.round(timePlayed)+"";
          // Count as complete only if end of video was reached
          if(timePlayed>=duration && event.type=="ended") {
            setWatchedVideos(vids => [...vids, content])
          }
        }
        
        
        video.addEventListener("play", videoStartedPlaying);
        video.addEventListener("playing", videoStartedPlaying);
        
        video.addEventListener("ended", videoStoppedPlaying);
        video.addEventListener("pause", videoStoppedPlaying);
    }

    useEffect(() => {
        checkVideoPlay();
    }, [content] )

    return (
        <div className='d-flex flex-column justify-content-center align-items-center m-2'
        style={{
            color: 'white',
        }}>
            <video id={content} src={content} style={{borderRadius: '5px', width: '100%'}} controls />
            <div>
                <span>Played </span>
                <span id="played">0</span><span> seconds out of </span>
                <span id="duration"></span><span> seconds. (only updates when the video pauses)</span>
            </div>
        </div>
    )
}

Solution

  • Wow... react developer error. I forgot to drill the props through all the templates... I only did one template.

    Each template used the same video content file... Answered!