Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use useRef on mount

I want to use useRef inside useeffect hook on component first mount, after that i would like to press a button to load other content besides that, on user click. My current implementation I get error that says Error: Objects are not valid as a React child (found: [object HTMLDivElement]). Which does not make sense to me. Here is my code.

import { useEffect, useState, useRef } from "react";
import { fetchData } from "./utils/fetchData";

export default function App() {

let previousEmail = useRef('');

const [email, setEmail] = useState('');

useEffect(() => {
  async function getEmail() {
    let title = await fetchData();
    console.log(title);
    previousEmail.current.textContent = title;

  }

   getEmail();
 }, [])

   const getRandomEmail = async () => {
   const emailAddress = await fetchData();
      setEmail(emailAddress)
   }


   return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <button onClick={getRandomEmail}>Button</button>
        <p>{email}</p>
        <label>Previous Email</label>
        <div ref={previousEmail}>{previousEmail.current}</div>
      </div>
     );
 }

Here is the code for my FetchData method

 const fetchData = async () => {
   const response = await fetch('https://randomuser.me/api');
   const data = await response.json();
   const emailData = data.results[0].email;
   return emailData;
 }

export {
   fetchData
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change

<div ref={previousEmail}>{previousEmail.current}</div>

to

<div ref={previousEmail}></div>.

I’m assuming you are trying to add previous email address to the div but you are actually adding a reference to the div which is an object and not allowed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading