how to use react-query with a Laravel api

Viewed 35

I am following a example that uses react-query, the example works fine with the test data, but when it hits a backend that I am building is not working as expected, I mean, it retrieves the information, but don't cache the information, always hits the server, but using the example, that was not happening.

hooks/user.js

import { useQuery } from "react-query";
import axios from "axios";    

export const useUsers = (activePage) => {
    return useQuery(
      // Add activePage as a dependency
      ["users", activePage],
      async () => {
        const { data } = await axios.get(
           //works fine here
          `https://reqres.in/api/users?page=${activePage}`

           //Here not works properly
          //`http://127.0.0.1:8000/api/users?page=${activePage}`
        );
   
        return data;
      },
      // This tells React-Query that this is Query is part of
      // a paginated component
      { keepPreviousData: true }
    );
};

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { QueryClient, QueryClientProvider } from "react-query";
import { ReactQueryDevtools } from "react-query/devtools";    
const queryClient = new QueryClient(); // Global Store Instance

ReactDOM.render(
 <QueryClientProvider client={queryClient}>
  <React.StrictMode>
    <App />
  </React.StrictMode>
   <ReactQueryDevtools initialIsOpen={false} />
  </QueryClientProvider>,
  document.getElementById('root')
);    

reportWebVitals();

App.js

import { useState } from "react";
import TableHeader from "./components/tableHeader/TableHeader";
import TableRow from "./components/tableRow/TableRow";
import Pagination from "./components/pagination/Pagination";
// Import the hook
import { useUsers } from "./hooks/users";

const App = () => {
 const [activePage, setActivePage] = useState(1);

 // React Query takes care of calling
 // userUsers hook when App.js is rendered.
 const usersList = useUsers(activePage);

 return (
   <>
     <TableHeader />
     {/* map through users list */}
     {usersList.data &&
       usersList.data.data.map((user) => <TableRow user={user} key={user.id} />)}
     <Pagination
       activePage={activePage}
       setActivePage={setActivePage}
       pages={2}
     />
   </>
 );
};

export default App;

In the example, when I hit the api again, I mean, I go to other page twice, in the network tab is says this: (disk cache)

Which is the expected behaviour, but when it is using my laravel api, then is not working properly, it is able to retrieve the information, but always hits the server, not the cache

In my laravel app I have this:

routes/api.php

Route::get('/users', [UsersController::class, 'index']);

UsersController.php

...
public function index()
    {

        return User::paginate(10);
    }
...

The frontend is using this url:

http://localhost:3000/

and the backend is using this:

http://localhost:8000/

maybe is because of the port? but using the external api: https://reqres.in/api/users?page=1 it works without problem, it uses the cache as expected, do weird. I think I need to modify my api

This is the response of my local api:

{
   "current_page":1,
   "data":[
      {
         "id":1,
         "first_name":"sergio",
         "avatar_url":"https:\/\/url",    
         "age":30,
         "created_at":"2022-09-11T22:29:52.000000Z",
         "updated_at":"2022-09-11T22:29:52.000000Z"
      },
      {
         "id":2,
         "first_name":"jhon",
         "avatar_url":"https:\/\/url",
         "age":39,
         "created_at":"2022-09-11T22:30:03.000000Z",
         "updated_at":"2022-09-11T22:30:03.000000Z"
      },
     ...
...
   ],
   "first_page_url":"http:\/\/127.0.0.1:8000\/api\/users?page=1",
   "from":1,
   "last_page":9,
   "last_page_url":"http:\/\/127.0.0.1:8000\/api\/users?page=9",   
   "next_page_url":"http:\/\/127.0.0.1:8000\/api\/users?page=2",
   "path":"http:\/\/127.0.0.1:8000\/api\/users",
   "per_page":3,
   "prev_page_url":null,
   "to":3,
   "total":25
}

What can I do? thanks.

1 Answers

Replace return in your controller by this one

return response()->json(User::paginate(10));
Related