DEV Community

Krunal Kanojiya
Krunal Kanojiya

Posted on

Fetching Data from an API in SolidJS with Axios with Example

To fetch data from an API in SolidJS with Axios, you can use the createEffect hook to make the API call and store the data in a state variable. But before we deep dive into a example, Let’s understand what createEffect can do in SolidJS.

The createEffect hook in SolidJS is used to create an effect that reacts to changes in observable values. An effect is a function that runs whenever its dependencies change.

The createEffect hook takes a function as its argument and returns a cleanup function that can be used to clean up any resources created by the effect. The function passed to createEffect can use any observable values as its dependencies, including state variables created with createSignal or createStore, or derived values created with createMemo.

The createEffect hook can be used for a wide variety of tasks, such as fetching data from an API, updating the DOM, or subscribing to events.

When an effect runs, any changes it makes to observable values will trigger a re-run of the effect. This can lead to infinite loops if not used carefully. To prevent infinite loops, you can use the untrack function to temporarily suspend tracking of observable changes within an effect, or you can use the createMemo hook to memoize derived values.

import { createSignal, createEffect } from 'solid-js';
import axios from 'axios';

function App() {
  const [data, setData] = createSignal(null);

  createEffect(() => {
    axios.get('https://api.example.com/data')
      .then(response => setData(response.data))
      .catch(error => console.error(error));
  });

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we first import the createSignal and createEffect functions from SolidJS and the axios library. We then create a state variable called data using the createSignal function and initialize it to null.

We then use the createEffect hook to make the API call using axios.get. When the API call succeeds, we set the data state variable to the response data using the setData function. If the API call fails, we log the error to the console.

Finally, we render the data in a list. If the data is still null, we display a “Loading…” message. Note that this example assumes that the API returns an array of objects with a name property. You will need to modify the code to fit your specific API’s data structure.

Overall, the createEffect hook is a powerful tool for creating reactive, declarative logic in SolidJS applications.

Top comments (2)

Collapse
 
christopherc1331 profile image
Christopher Cruz • Edited

SolidJs has built in tooling for conditionally rendering, as well as iterative rendering. Instead you could refactor your code like below. Lastly when accessing the value from a signal you have to invoke the getter function data().

<Show when={data()} fallBack={<p>Loading...</p>}>
....<ul>
........<For each={data()}>{item =>
............<li>{item.name}</li>
........}</For>
....</ul>
</Show>

Collapse
 
xyz123 profile image
X YZ

I think that's what createResource is for