Joaquin86
Joaquin86

Reputation: 116

send function to child component hooks

edited: solved, missing curly brakets in arguments

hope you can clarify this issue: I have parent component:

function App() {
const [change, setChange] = useState(true);


const handleChange=(mode)=>{
  setChange(mode);
  console.log('change',change);
  
}

  return (
    <>
    
      <Navigation modes={handleChange}/>

and I am trying to send handlechange to the child component to change "change" state(sorry for the naming). I have the child component as it follows:

export default function Navigation({modes}) {
    const [mode, setMode] = useState(true);

const handleMode=(mode)=>{
        setMode(mode)
    }

useEffect(() => {
        modes(mode);
       }, [ mode ]);

return (
        
            
                <div className="nav__switch">
                    <Switch handleMode={handleMode}/>
                </div>

       

and the final component, the one that will update the mode:

export default function Switch({modes}) {
    const [mode, setMode] = useState(true);


    useEffect(() => {
        modes(mode)
      }, [mode]);

    const modeChange=()=>{

        mode?setMode(false):setMode(true);
        console.log(mode)
    }

there is a modeChange function that changes the state of mode that will be taken as an argument for the function on the parent element, however I am getting the error saying that "modes" is not a function, I console logged it and I can see that it is an object with default properties.

Does anybody knows what I am doing wrong here?

thanks

Upvotes: 0

Views: 49

Answers (1)

Shehan Hasintha
Shehan Hasintha

Reputation: 1165

I think you are doing it right but you are not waiting until it sets the state. you are console logging before the that makes the change happens. you need to wait until it does change. I think you should wait for a moment and see if it works. wrap your console.log with set interval function and see it if there is any difference

setTimeout(function(){ console.log(mode); }, 3000);

I this kind of cases you have to use js promises, async, awaits to make the execution wait until the task is done. checkout the documentation about promises here

Upvotes: 1

Related Questions