I have a React component with two functions: one that fetches data (getData) and one that sends the data (sendData). When a button is clicked, I want the following to happen: if getData has not been called before, getData should be called first, then sendData. If getData has been called before, sendData should be called directly.
Here is the structure I have built:
import { useState } from "react";
export function App() {
const [data, setData] = useState(null);
const getData = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const result = await response.json();
setData(result);
}
const sendData = () => {
console.log(data);
// data sending operations
}
const handleClick = async () => {
if (!data) {
await getData();
}
sendData();
}
return (
<button onClick={handleClick}>Click me!</button>
);
}
You can see the code in this React playground
Here is the problem: sendData is called right after getData completes, and since our state (data) hasn’t been updated yet, sendData can’t see the current state.
Of course, the first solution that comes to mind is to have getData return the data and pass the returned data as a parameter to sendData. But if for some reason we don’t want to do that, can we find another solution? I thought of using useEffect, but I don’t need sendData to be called when the state is updated. I only need it to be called when I press the button.