Reputation: 338
I'm trying to call an endpoint in an api that returns a value, I have a dream to call this fetch function inside another function, then save it to a variable.
But this returns a promise or if I get it working the function calls other things before the returned value.
Is the only way to do a timeout?
Here is a code example
async function someFetch() {
const res = await fetch("someurl");
const data = res.json();
return data;
}
function useFetched(someInput1, someInput2) {
const fetchedData = someFetch(); // need this input before anything else is called
const some_var = fetchedData + someInput1 + someInput2;
return some_var;
}
I've also tried to make the second function async and called await in front of someFetch(), but this returns a promise.
Upvotes: 0
Views: 1017
Reputation: 8135
You cant make async useFetch[hook]
. You need to use a callback here. The rough idea, you can pass setter function to useFetch
to set value. And then can use that value.
Sample:
async function fetchTodo() {
const res = await fetch("someurl");
const data = res.json();
return data;
}
function useFetched(id, callback) {
useEffect(() => {
fetchTodo(id).then(data => {
console.log(data);
callback(data);
});
}, [id, callback]);
}
Working sample:
import React, { useEffect, useState } from "react";
async function fetchTodo(id) {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/" + id);
const data = res.json();
return data;
}
function useFetched(id, callback) {
useEffect(() => {
fetchTodo(id).then(data => {
console.log(data);
callback(data);
});
}, [id, callback]);
}
export default function App() {
const [data, setData] = useState({});
useFetched(1, setData);
if (!data) return <h1>Loading...</h1>;
return (
<div className="App">
<h1>{JSON.stringify(data)}</h1>
</div>
);
}
Sandbox: https://codesandbox.io/s/misty-smoke-ls2y4?file=/src/App.js:0-607
Upvotes: 0
Reputation: 778
You need need to await
the result of someFetch
async function useFetched(someInput1, someInput2){
const fetchedData = await someFetch() // need this input before anything else is called
const some_var = fetchedData + someInput1 + someInput2
return some_var
}
Upvotes: 1