Search code examples
reactjsonclickreact-router-dommulti-page-application

Warning: Expected `onClick` listener to be a function, instead got a value of `boolean` type


I am working with react. When I try to play audio from a button I am receiving this error. Everything worked before when the website was only a one page website. Then I turned it into a multi-page website using react-router-dom router, switch, and route everything started to error out with the onClick. I am not sure what went wrong or how to fix it. I am still pretty new with react. Here is the code:

Player.js

import React, { useState } from "react";
import "./Button.css";
import {useTranslation} from "react-i18next";
import teaser from '../sounds/teaser-final.mp3';


const Player = ({ url }) => {
  const useAudio = url => {
    const [audio] = useState(new Audio(teaser));
    const [playing, setPlaying] = useState(true); //nothing is playing on default
  
  const toggle = () => {
      setPlaying(!playing);
      playing ? audio.play() : audio.pause()
      console.log("audio is playing" + toggle);
     };
  
    return [playing, toggle];
  };

  const [toggle] = useAudio(url);

  const {t} = useTranslation('common');
  return (
    <div>
      <audio id="player" style={{'display': 'none'}} src={teaser}></audio>
      <button 
      className="btns hero-button btn--outline btn--large"
      onClick={toggle}
      >
      {t('heroSection.button')}
      </button>
    </div>
  );
};

export default Player;

HeroSection.js (file where Player.js is used)

import React from 'react'
import './HeroSection.css'
import Player from '../Player';

function HeroSection() {  
    return (
        <div className="hero-btns">
           <Player />
        </div>
        
    )
}

export default HeroSection;

App.js

import React, { useState, useEffect } from 'react';
import './index.css';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import Axios from 'axios';
import AdminHome from './Components/auth/Admin';
import Login from './Components/auth/Login';
import Register from './Components/auth/Register';
import UserContext from './Context/UserContext';

import Navbar from './Components/Navbar/Navbar';
import HeroSection from './Components/HeroSection/HeroSection';
import ShareSection from './Components/ShareSection/ShareSection';
import Subscribe from './Components/Subscribe/Subscribe';
import Footer from './Components/Footer/Footer';
import About from './Components/About/About';
import TheApp from './Components/TheApp/TheApp';
import Contact from './Components/SocialSection/Contact';
import CookiesPopUp from './Components/Cookies/CookiesPopUp';

function Home() {
  return (
      <>
          <CookiesPopUp />
          <Navbar />
          <HeroSection />
          <ShareSection />
          <Subscribe />
          <TheApp />
          <About />
          <Contact />
          <Footer />
      </>
  );
};

function App() {
  const [userData, setUserData] = useState({
    token: undefined,
    user: undefined,
  });
  const [didMount, setDidMount] = useState(false);

  useEffect(() => {
    setDidMount(true);
    
    const checkedLoggedIn = async () => {
        let token = localStorage.getItem("auth-token");
        if(token === null) {
            localStorage.setItem("auth-token", "");
            token = "";
        }
        const tokenRes = await Axios.post(
            "http://localhost:5000/users/tokenIsValid", null, 
            {headers: { "x-auth-token": token }}
        );
        if (tokenRes.data) {
            const userRes = await Axios.get("http://localhost:5000/users/", {
                headers: { "x-auth-token": token },
            });
            setUserData({
                token,
                user: userRes.data,
            });
        }
        return () => setDidMount(false);
    };
    checkedLoggedIn();
  }, [])

  if(!didMount) {
    return null;
  }

  return (
    <>
      <BrowserRouter>
        <UserContext.Provider value={{userData, setUserData}}>
          <Switch>
            <Route path="/" component={Home} exact />
            <Route path="/admin" component={AdminHome} exact />
            <Route path="/admin/login" component={Login} exact />
            <Route path="/admin/register" component={Register} exact />
          </Switch>
        </UserContext.Provider>
      </BrowserRouter>
    </>
  );
}

export default App;

And this is the error I get in console when I try to play the audio.

This is the error I receive.


Solution

  • You are overriding the definition of toggle with this code : const [toggle] = useAudio(url);. The Player.js has multiple declarations and definitions of toggle. See:

     const toggle = () => {
          setPlaying(!playing);
          playing ? audio.play() : audio.pause()
          console.log("audio is playing" + toggle);
         };
      
        return [playing, toggle];
      };
    
    ..
    ...
    ..
    const [toggle] = useAudio(url);
    
    

    Hence the Error Expected OnClick to be a function but provided a boolean