I've created a simple example https://codesandbox.io/s/4zq852m7j0.
As you can see I'm fetching some data from a remote source. I'd like to use the return value as the value inside my textfield.
const useFetch = () => {
const [value, setValue] = useState("");
useEffect(
async () => {
const response = await fetch("https://httpbin.org/get?foo=bar");
const data = await response.json();
setValue(data.args.foo);
},
[value]
);
return value;
};
However using the value inside the useState function does not work. I think useState uses the default value only on first render. When first rendering the value is obviously not set since it's async. The textfield should have the value bar but it is empty.
function App() {
const remoteName = useFetch();
// i want to see the remote value inside my textfield
const [name, setName] = useState(remoteName);
const onChange = event => {
setName(event.target.value);
};
return (
<div className="App">
<p>remote name: {remoteName}</p>
<p>local name: {name}</p>
<input onChange={onChange} value={name} />
</div>
);
}
After fetching the value from remote I'd like to be able to change it locally.
Any ideas?