Home > Software design >  How to use useRef on mount
How to use useRef on mount

Time:01-04

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
}

CodePudding user response:

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.

CodePudding user response:

Ref's aren't intended for this purpose. If you need to update what's on the page then you should have a state value, and when you set state the component rerenders. Here's the standard way of doing this:

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

useEffect(() => {
  async function getEmail() {
    let title = await fetchData();
    setPreviousEmail(title);
  }

  getEmail();
}, [])

return (
  <div className="App">
    <h1>Hello CodeSandbox</h1>
    <button onClick={getRandomEmail}>Button</button>
    <p>{email}</p>
    <label>Previous Email</label>
    <div>{previousEmail}</div>
  </div>
)
  •  Tags:  
  • Related