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
}
>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.