0

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
problème0123
  • 841
  • 2
  • 9
  • 23
  • 1
    Does this answer your question? [Rendering remote data using the fetch API in SolidJS](https://stackoverflow.com/questions/74589998/rendering-remote-data-using-the-fetch-api-in-solidjs) – snnsnn May 29 '23 at 19:15
  • Hello, thank for your help. – problème0123 Jun 03 '23 at 17:40

0 Answers0