I have an API.jsx component and a Consume.jsx component. In the API.jsx files, I have grouped all my functions allowing to query the backed in a class In Consume.jsx, I want to call the function to get the data.
API.jsx
import { createSignal, onCleanup } from "solid-js";
class API {
static backendURL = "...";
fetchPersons() {
const [persons, setPersons] = createSignal([]);
async function getPersons() {
try {
const response = await fetch(`${API.backendURL}/api/persons/`);
const data = await response.json();
setPersons(data);
} catch (error) {
console.error("Error", error);
}
}
getPersons();
return persons;
}
}
export default new API();
Consume.tsx
import { createSignal } from 'solid-js';
import API from './API';
const Table = () => {
const [persons, setPersons] = createSignal([]);
const data = await fetchPersons();
setPersons(data);
console.log(persons());
return <div></div>;
};
export default Table;
In the console i get BoundFunctionObject { … }.
I know I am calling it directly without waiting for the response from the getPersons function which makes the asynchronous request. How can i solve this ?
Correction
API.tsx
const backendURL: string = "...";
async function getPersons() {
const response = await fetch(`${backendURL}/api/persons/`);
const data = await response.json();
return data;
}
const API = {
getPersons,
};
export default API;
Consume.tsx
import API from './API';
const Table = () => {
const [data] = createResource(API.getPersons);
return (...)
};
export default Consume