skip to Main Content

I’m new to SolidJS and React. I’m trying to make a custom hook that will return whatever response I get from an API, then pass that data to components.

The problem is I get empty arrays when i call the hook in the component.

This is the hook:

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

function useFetch(url){

    const [data,signalData] = createSignal(null)

    createEffect(() =>
    {
        axios.get(url).then((response) => 
            
            {signalData(response.data.data)
                console.log(data())
            }

        ).catch(err =>console.log(err))
    },[url])

    return data();
}
export default useFetch;

and im trying to call it in this component:

function Club_window(){

    
    const data = useFetch('http://localhost:8080/team?team_id=151')
    console.log(data)

    return(

    <div class={main_menu_clubCSS.club_window}>
    <div class={main_menu_clubCSS.img_wrapper}>
        <img class={main_menu_clubCSS.img_blur} src='https://cdn.footystats.org/img/teams/england-liverpool-fc.png'/>
        <div class={main_menu_clubCSS.club_content}>
                <p><span>BIGGER CLUB</span><span>Test</span></p>
        </div>
    </div>
</div>
)}
export default Club_window;

The console.log(data()) in the hook logs the data but when i console.log(data) in the component, its null or empty. What am i doing wrong? Ive tried putting the return data(); in other places in the hook, ive tried just return data; nothing works.. Thanks!

2

Answers


  1. React and Solid have completely different execution model and their code can not be cross compiled.

    The effect inside the useFetch function is totally unnecessary and it overwrites the signal’s value whenever it get updated. Plus, it has React style dependency management, which is not supported in Solid.

    Solid provides resource API for data fetching.

    https://www.solidjs.com/docs/latest/api#createresource

    Resource is abstraction over fetch API but it is a convenience and you don’t have to use it. Check out this answer to see how to fetch remote data using both the resource API and fetch API in Solid.

    Rendering remote data using the fetch API in SolidJS

    Login or Signup to reply.
  2. Function in solid only gonna run once, when your async function get the data it’s not gonna trigger the console.log to rerun. try it inside JSX and invoke the accessor "data()"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search