Search code examples
reactjsredux-toolkitrtk-querysupabase

How to use RTK-Query with Supabase


I have a project already configured with Supabase and using Redux-Toolkit. I have never used RTK-Query and I am just learning but after reading in the docs and looking for similar questions I have created a supabaseApi.js file which looks like:

import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query';

export const supabaseApi = createApi({   baseQuery: fakeBaseQuery(),
    endpoints: (builder) =({
        getStudents: builder.query({
            queryFn: async () ={
                const students = await supabase
                .from('students')
                .select()

                return {students, error}
            }
        })
    }) })

export const { useGetStudentsQuery } = supabaseApi;

However, when I call the useGetStudentsQuery() to get the students table I receive an error in the console telling me that "useGetStudentsQuery is not a function". I also noticed that when I begin to write the useGet function, it seems it hasn't been automatically created as I don't get the Visual Studio hints.

What is it that I am doing wrong? Thanks.


Solution

  • A few things:

    • to have the hooks, you have to import from '@reduxjs/toolkit/query/react';
    • the queryFn has to return either { data } or { error }, not { student }
    • your code does not seem to have a error variable, but tries to return it.

    so:

    import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query/react';
    
    export const supabaseApi = createApi({   baseQuery: fakeBaseQuery(),
        endpoints: (builder) =({
            getStudents: builder.query({
                queryFn: async () ={
                    const students = await supabase
                    .from('students')
                    .select()
    
                    return { data: students }
                }
            })
        }) })
    
    export const { useGetStudentsQuery } = supabaseApi;