Jenssen
Jenssen

Reputation: 1871

Laravel Inertia React preserve state not working

I'm trying to reload my page but keep the filters state with Inertia.

Like this:

const [allProducts, setAllProducts] = useState([]);
    
const [filters, setFilters] = useState([]);

const fetchProducts = (page) => {
    Inertia.get(
      `/products?page=${page}`,
      { filters },
      {
        preserveState: true,
        preserveScroll: true,
        only: ['products'],
        onSuccess: (response) => {
          setAllProducts(allProducts.concat(response.props.products.data));
          page += 1;
        }
      }
    )
});

The problem is that filters and allProducts are reset even though preserveState = true.

Upvotes: 1

Views: 1483

Answers (2)

Danushka Madushanka
Danushka Madushanka

Reputation: 169

In your Controller try to use withQueryString() method. as a Example:

$allUsers = User::where('id', '!=', Auth::id())
            ->when($request->input('search'), function ($query, $search) {
                $query->where(function ($query) use ($search) {
                    $query->where('name', 'like', '%' . $search . '%')
                        ->orWhere('email', 'like', '%' . $search . '%');
                });
            })
            ->paginate(10)
            ->withQueryString()
            ->onEachSide(2);

Upvotes: 0

Erik Roznbeker
Erik Roznbeker

Reputation: 734

What do you mean by "reload my page"? State in React is not preserved on "real" page refresh.

Maybe you can save data in local storage, then load it by useEffect. Another solution is to store data you want to keep between pages in Laravel session storage.

Upvotes: 0

Related Questions