Get data from store - RTK Query

Viewed 50

I've started learning RTQ Query. For example i have following setup in service.ts:

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

const dataApi = createApi({
  reducerPath: 'reducerApi',
  baseQuery: fetchBaseQuery({
    baseUrl: 'someApiUrl',
  }),
  endpoints: (builder) => ({
    getByName: builder.query({
      query: (name: string) => name`,
    }),
  });

export default dataApi;

and then i use useLazyQuery hook in triggerComponent.tsx to get the data on button click and get the argument from input like this:

const TriggerComponent = () => {
  const [inputValue, setInputValue] = useState<string>('');
  const { useLazyGetByNameQuery } = dataApi;
  const [trigger] = useLazyGetByNameQuery();

  const handleClick = () => {
    void trigger(inputValue);
  };

return (
   <input
     label="Search"
     value={inputValue}
     onChange={(event) => setInputValue(event.target.value)}
   />
   <button onClick={handleClick}>
     Search
   </button>
)

and then I want to access this data in another component, but here comes my problem. I don't know how to get fetched data from created store. In ReduxDevTools I can see that data is fetched correctly of course. Any advices?

1 Answers

You have few options:

  1. Call the same query in the component where you have this data. And enable caching by providing a second argument, see docs.
  2. Or create selector and select from query result. There are examples in docs
Related