I'm new to useEffect and trying to get my head around it. I have data coming in via useEffect when a user logs in. The below function for useEffect is called and this does work but I have to refresh the page to see the value of "topic" change. I understand that this is because the value hasn't changed since the page loaded.
What I don't understand is: how do I make that state refresh so when the page is first loaded the data from useEffect is shown instead of an empty string?
Thanks!
<p> Topic: {topic} </p>;
const [topic, setTopic] = useState("");
useEffect(async () => {
const result = await axios({
method: "GET",
withCredentials: true,
url: "http://localhost:4000/userData",
}).then((res) => {
setData(res.data);
setTopic(res.data.topic);
});
}, []);
CodePudding user response:
You need to return what you want to be rendered from your function, just having <p> Topic: {topic} </p>;
sitting there doesn't do anything. You need to move it to the bottom and wrap it in return, like:
return(
<p> Topic: {topic} </p>
)
CodePudding user response:
You can't pass async function inside the useEffect as a argument. But you can use async function inside the normal function of useEffect (write there and call there).
Here, empty [] means it runs only once when component mounted(loaded) and you write something [counter] then it runs everytime counter value changes.
useEffect(() => {
const fetchResults = async () => {
const result = await axios({
method: 'GET',
url: 'http://localhost:4000/userData',
});
setData(result.data);
setTopic(result.data.topic);
};
fetchResults();
}, []);