Laurence Fass
Laurence Fass

Reputation: 1942

Redux Toolkit: how to write the getposts endpoint in official documentation

I am trying to learn RTKQuery but some of the documentation and examples are incomplete.

This link refers to a useGetPostsQuery but doesnt actually define the endpoint for it in the docs.

https://redux-toolkit.js.org/rtk-query/usage/queries#selecting-data-from-a-query-result

function PostsList() {
  const { data: posts } = api.useGetPostsQuery() // what does the endpoint look like?

  return (
    <ul>
      {posts?.data?.map((post) => (
        <PostById key={post.id} id={post.id} />
      ))}
    </ul>
  )
}

In absence of a working example am trying to write my own getMultipleItems endpoint and I am seeing TS errors. Ive modified the documentations pokemon example to also query a list from the api. live sandbox:

https://codesandbox.io/s/rtk-query-multi-fetch-poll-r4m2r

export const pokemonApi = createApi({
  reducerPath: "pokemonApi",
  baseQuery: fetchBaseQuery({ baseUrl: "https://pokeapi.co/api/v2/" }),
  tagTypes: [],
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: (name: string) => `pokemon/${name}`
    }),
    // this is meant to get all pokemon but is causing type errors
    getAllPokemon: builder.query({
      query: () => `pokemon/`
    })
  })
});

to focus on the relevant endpoint, the getAllPokemon doesnt have any args:

    getAllPokemon: builder.query({
      query: () => `pokemon/`
    })

then i try to use it here but useGetAllPokemonQuery doesnt have the correct signature and appears to be expecting args.

export const PokemonList = () => {
  const { data, error, isLoading } = useGetAllPokemonQuery();
  return (
    <>
      {error ? (
        <p>Fetch error</p>
      ) : isLoading ? (
        <p>Loading...</p>
      ) : data ? (
        <>
          <p>map pokemon here</p>
        </>
      ) : null}
    </>
  );
};

My question is: how do i correctly construct the endpoint to use it in the component example show above?

Upvotes: 0

Views: 421

Answers (1)

phry
phry

Reputation: 44236

In your case:

    getAllPokemon: builder.query<YourResultType, void>({
      query: () => `pokemon/`
    })

which uses void for the "argument type".

For what it's worth, all the examples under https://github.com/reduxjs/redux-toolkit/tree/master/examples/query/react are in TypeScript. You might just want to look at those.

Upvotes: 2

Related Questions