### Install Phetch via .NET CLI Source: https://github.com/jcparkyn/phetch/blob/main/README.md Provides the command to install the Phetch.Blazor NuGet package using the .NET CLI. This command adds the necessary package reference to your project file. ```sh dotnet add package Phetch.Blazor ``` -------------------------------- ### Polly Integration for Advanced Retries Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/retries.md Demonstrates integrating Phetch with Polly for advanced retry strategies. It includes an adapter class and an example of creating a Polly policy and passing it to Phetch endpoint options. ```cs using Phetch.Core; using Polly; public sealed record PollyRetryHandler(IAsyncPolicy Policy) : IRetryHandler { public Task ExecuteAsync(Func> queryFn, CancellationToken ct) => Policy.ExecuteAsync(queryFn, ct); } ``` ```cs var policy = Policy .Handle() .RetryAsync(retryCount); var endpointOptions = new EndpointOptions { RetryHandler = new PollyRetryHandler(policy) }; ``` -------------------------------- ### Create Endpoint with Modified Default Options in C# Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/sharing-options-between-endpoints.md This C# example demonstrates creating a new `Endpoint` instance using a modified copy of the default `EndpointOptions`. It overrides the `CacheTime` for this specific endpoint while inheriting other settings from the default instance. ```cs var isEvenEndpoint = new Endpoint( GetIsEvenAsync, // Put your query function here options: new(defaultEndpointOptions) { CacheTime = TimeSpan.FromMinutes(10), } ); ``` -------------------------------- ### Define Async Endpoint in C# Source: https://github.com/jcparkyn/phetch/blob/main/README.md Defines a reusable asynchronous endpoint for Phetch. This example shows how to create an endpoint that takes an integer and returns a boolean, checking if the number is even by calling an external API. It requires the Phetch.Core library and an HttpClient. ```cs using Phetch.Core; // This defines an endpoint that takes an int and returns a bool. var isEvenEndpoint = new Endpoint( // Replace this part with your own async function: async (value, cancellationToken) => { var response = await httpClient.GetFromJsonAsync( $"https://api.isevenapi.xyz/api/iseven/{value}", cancellationToken); return response.IsEven; } ); ``` -------------------------------- ### Define an Integer to Thing Endpoint with Dependencies Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/defining-query-endpoints.md This example shows how to define a Phetch `Endpoint` within a class that has dependencies, such as `HttpClient`. The `GetThingEndpoint` is designed to retrieve a 'Thing' object based on an integer ID. Dependencies are injected via the constructor. ```cs public class MyApi { // An endpoint to retrieve a thing based on its ID public Endpoint GetThingEndpoint { get; } // If your code has dependencies on other services (e.g., HttpClient), // you can add them as constructor parameters. public MyApi(HttpClient httpClient) { GetThingEndpoint = new( // TODO: Put your query function here. ); } } ``` -------------------------------- ### Define an Integer to Boolean Endpoint Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/defining-query-endpoints.md This snippet demonstrates how to define a Phetch `Endpoint` that accepts an integer and returns a boolean. It includes an example of an asynchronous function that fetches data from an external API to determine if a number is even. The `httpClient` is used for making the GET request. ```cs var isEvenEndpoint = new Endpoint( // Replace this part with your own async function: async (value, cancellationToken) => { var response = await httpClient.GetFromJsonAsync( $"https://api.isevenapi.xyz/api/iseven/{value}", cancellationToken); return response.IsEven; } ); ``` -------------------------------- ### Inject Phetch Service in Blazor Component Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/defining-query-endpoints.md This example demonstrates how to inject a custom API service, like `MyApi` which uses Phetch endpoints, into a Blazor component. It shows the usage of the `@inject` directive to make the `Api` service available within the component's Razor markup. ```cshtml @inject MyApi Api ``` -------------------------------- ### C# Phetch: Invalidate Query Data on Success Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/invalidation-and-pessimistic-updates.md This C# example demonstrates how to automatically invalidate cached data for a specific query (`GetThingEndpoint`) whenever another query (`UpdateThingEndpoint`) successfully completes. It uses the `OnSuccess` event handler within the `Endpoint` options to trigger the invalidation based on the arguments of the successful query. ```cs public class ExampleApi { // An endpoint to retrieve a thing based on its ID public Endpoint GetThingEndpoint { get; } // An endpoint with one parameter (the updated thing) and no return public ResultlessEndpoint UpdateThingEndpoint { get; } public ExampleApi() { GetThingEndpoint = new(GetThingByIdAsync); UpdateThingEndpoint = new(UpdateThingAsync, options: new() { // Automatically invalidate the cached value for this Thing in GetThingEndpoint, // every time this query succeeds. OnSuccess = eventArgs => GetThingEndpoint.Invalidate(eventArgs.Arg.Id) }); } async Task UpdateThingAsync(Thing thing, CancellationToken ct) { // TODO: Make an HTTP request to update thing } async Task GetThingByIdAsync(int thingId, CancellationToken ct) { // TODO: Make an HTTP request to get thing } record Thing(int Id, string Name); } ``` -------------------------------- ### Handle Query Loading, Error, and Success States in Blazor Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/faq.md This C# code snippet demonstrates a common pattern for handling the different states of a query (loading, error, success) in a Blazor component. It checks for `IsLoading`, `IsError`, and `HasData` to render appropriate UI elements. It also includes an optional check for `IsFetching` to indicate background updates. ```cs @if(query.IsLoading) { // render loading indicator or skeleton } else if (query.IsError) { // render error message } else if (query.HasData) { // remove this check if data can be null if (query.IsFetching) { // optional: render background fetch indicator } // render data } ``` -------------------------------- ### Preload Hacker News Front Page Data (JavaScript) Source: https://github.com/jcparkyn/phetch/blob/main/samples/HackerNewsClient/wwwroot/index.html This script preloads the front page data for Hacker News when the user is on the root path. It creates a link element with 'preload' attributes to fetch the data asynchronously, improving perceived performance. ```javascript if (window.location.pathname === "/") { const preloadLink = document.createElement("link"); preloadLink.rel = "preload"; preloadLink.href = "https://hn.algolia.com/api/v1/search?tags=front_page&query=&hitsPerPage=100&page=0"; preloadLink.as = "fetch"; preloadLink.crossOrigin = true; document.head.appendChild(preloadLink); } ``` -------------------------------- ### ObserveQuery Component Usage in Blazor Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/using-query-objects-directly.md Demonstrates how to use the component in Blazor to manage and display data fetched via a Phetch Query object. It shows how to initialize the query, set arguments, conditionally render content based on query data, and properly dispose of the query to prevent memory leaks. ```cshtml @implements IDisposable @inject MyApi Api @{ query.SetArg(ThingId); } @* Put content that depends on the query here. *@ @if (query.HasData) { // etc... } @code { private Query query = null!; [Parameter] public int ThingId { get; set; } protected override void OnInitialized() { query = Api.GetThing.Use(); } // Disposing the query signals to the cache that the result is no longer being used, and avoids memory leaks. public void Dispose() => query.Dispose(); } ``` -------------------------------- ### Using `` with Data Fetching Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/useendpoint.md This Blazor component demonstrates how to use the `` component to fetch and display data from a query endpoint. It injects a service (`MyApi`), uses the endpoint with an argument (`Arg`), and conditionally renders content based on the query's state (has data, loading, or error). ```cshtml @*This assumes you've created a class called MyApi containing your endpoints, and registered it as a singleton or scoped service for dependency injection. *@ @inject MyApi Api @if (query.HasData) {

Thing Name: @query.Data.Name

} else if (query.IsLoading) {

Loading...

} else if (query.IsError) {

Error: @query.Error.Message

}
@code { [Parameter] public int ThingId { get; set; } } ``` -------------------------------- ### Define Phetch Endpoint with Tuple Parameters (C#) Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/endpoints-with-multiple-parameters.md Demonstrates how to create a Phetch endpoint that accepts multiple parameters by combining them into a C# tuple. This approach is useful for endpoints requiring a search term and a page number. ```cs var endpoint = new Endpoint<(string searchTerm, int page), List>( (args, ct) => GetThingsAsync(args.searchTerm, args.page, ct) ) ``` -------------------------------- ### Using ParameterlessEndpoint in Phetch Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/endpoints-without-parameters.md Demonstrates how to use the `ParameterlessEndpoint` class for Phetch endpoints that do not accept any parameters. This is typically used within a component via the `` component. ```javascript import { ParameterlessEndpoint } from "phetch"; // Example usage within a component: // ``` ```typescript import { ParameterlessEndpoint } from "phetch"; // Example usage within a component: // ``` -------------------------------- ### Define Default Endpoint Options in C# Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/sharing-options-between-endpoints.md This snippet shows how to create a default `EndpointOptions` instance in C#. It configures cache time, a failure event handler, and a simple retry mechanism. This instance can then be reused across multiple endpoints. ```cs var defaultEndpointOptions = new EndpointOptions { CacheTime = TimeSpan.FromMinutes(2), OnFailure = event => Console.WriteLine(event.Exception.Message), RetryHandler = RetryHandler.Simple(2), }; ``` -------------------------------- ### Use Endpoint in Blazor Component Source: https://github.com/jcparkyn/phetch/blob/main/README.md Demonstrates how to use a Phetch endpoint within a Blazor component using the `UseEndpoint` tag. It displays different content based on the query's state (error, loading, or data available). The `Arg` parameter triggers re-fetching when changed. ```cshtml @using Phetch.Blazor @if (query.IsError) {

Something went wrong!

} else if (query.IsLoading) {

Loading...

} else if (query.HasData) {

The number is @(query.Data ? "even" : "odd")

}
``` -------------------------------- ### Using ResultlessEndpoint in Phetch Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/endpoints-without-parameters.md Explains the usage of the `ResultlessEndpoint` class for Phetch endpoints that do not return any value. This class is used with the standard `` component. ```javascript import { ResultlessEndpoint } from "phetch"; // Example usage within a component: // ``` ```typescript import { ResultlessEndpoint } from "phetch"; // Example usage within a component: // ``` -------------------------------- ### Prefetch Data with Endpoint Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/pre-fetching.md Triggers a request to fetch data ahead of time and stores the result in the cache. This is useful for anticipating future data needs, such as loading the next page of a table. ```csharp endpoint.Prefetch(arg) ``` -------------------------------- ### Register Phetch Service in Program.cs Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/defining-query-endpoints.md This code snippet illustrates how to register a custom API service, which contains Phetch endpoints, with Blazor's dependency injection system in the `Program.cs` file. It uses `AddScoped` to register the `MyApi` service. ```cs builder.Services.AddScoped(); ``` -------------------------------- ### Triggering Re-render with ObserveQuery OnChanged Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/using-query-objects-directly.md Illustrates how to force a component re-render when the query state changes by using the `OnChanged` parameter of the component with the `StateHasChanged` method in Blazor. ```cshtml ``` -------------------------------- ### Configure RefetchInterval in Phetch Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/caching-and-staleness.md Enable automatic background refetching of query data at a specified interval. The shortest interval is used if multiple components observe the same query. ```csharp var endpoint = new Endpoint("/my-data"); // Refetch every 30 seconds: var data = endpoint.Use(new EndpointUseOptions { RefetchInterval = TimeSpan.FromSeconds(30) }); // In a component: // ``` -------------------------------- ### Simple Retries with RetryHandler.Simple Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/retries.md Configures an endpoint to retry a fixed number of times on any exception (except cancellation) using RetryHandler.Simple. ```cs var isEvenEndpoint = new Endpoint( GetIsEvenAsync, // Put you query function here options: new() { // Retry a maximum of two times on any exception (except cancellation) RetryHandler = RetryHandler.Simple(2) } ); ``` -------------------------------- ### Update Query Data in Cache Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/pre-fetching.md Adds or updates a cache entry with specific data without re-executing the query. This allows for manual control over cached data. ```csharp endpoint.UpdateQueryData(arg, data) ``` -------------------------------- ### Scroll to Element by ID (JavaScript) Source: https://github.com/jcparkyn/phetch/blob/main/samples/HackerNewsClient/wwwroot/index.html This JavaScript function, scrollIntoView, sets the page's target by updating the window's location hash with the ID of the provided element. This is intended to work with frameworks like Blazor to automatically scroll to the specified element. ```javascript function scrollIntoView(element) { // Sets the page target. Blazor will automatically scroll to it. window.location.hash = element.id; } ``` -------------------------------- ### Phetch Query: Async Variants for Result Handling Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/invoking-queries-manually.md Async variants of SetArg, Refetch, and Trigger return the query result or re-throw exceptions. Use these when you need to await the query's outcome or handle potential errors explicitly. ```javascript // Example for TriggerAsync async function runMutation() { try { const result = await query.TriggerAsync(payload); console.log('Success:', result); } catch (error) { console.error('Error:', error); } } ``` -------------------------------- ### Phetch Query: Refetch for Background Re-fetching Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/invoking-queries-manually.md The Refetch method re-fetches a query in the background. It utilizes the last argument provided via SetArg for the re-fetch operation. ```javascript query.Refetch(); ``` -------------------------------- ### Configure StaleTime in Phetch Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/caching-and-staleness.md Customize the duration before cached data is considered stale, influencing background refetching. Set to TimeSpan.MaxValue to prevent staleness. ```csharp var endpoint = new Endpoint("/my-data", new EndpointOptions { StaleTime = TimeSpan.FromMinutes(5) }); // Or to override for a specific usage: var data = endpoint.Use(new EndpointUseOptions { StaleTime = TimeSpan.FromHours(1) }); // To prevent data from ever becoming stale: var neverStaleEndpoint = new Endpoint("/never-stale-data", new EndpointOptions { StaleTime = TimeSpan.MaxValue }); ``` -------------------------------- ### Cancel a Running Query Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/cancelling-queries.md Demonstrates how to cancel a query that is currently executing. Calling `query.Cancel()` immediately resets the query's state to its pre-execution status and cancels the associated `CancellationToken`. ```Go query.Cancel() ``` -------------------------------- ### Configure CacheTime in Phetch Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/caching-and-staleness.md Set the duration for which cached results persist if not actively used. Use TimeSpan.MaxValue for indefinite caching. ```csharp var endpoint = new Endpoint("/my-data", new EndpointOptions { CacheTime = TimeSpan.FromMinutes(10) }); // To make cached values last forever: var foreverCacheEndpoint = new Endpoint("/forever-cache-data", new EndpointOptions { CacheTime = TimeSpan.MaxValue }); ``` -------------------------------- ### Phetch Query: Invoke for Direct Function Call Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/invoking-queries-manually.md The Invoke method directly calls the original query function, bypassing all Phetch caching and state management functionalities. This is useful for scenarios where Phetch's overhead is not desired. ```javascript query.Invoke(argument); ``` -------------------------------- ### Phetch Query: SetArg for Argument Updates Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/invoking-queries-manually.md The SetArg method updates a query's argument and automatically re-fetches if the argument has changed. It prevents re-fetching if the same argument is passed consecutively. This is the internal mechanism used by ``. ```javascript query.SetArg(newArgument); ``` -------------------------------- ### Phetch Query: Trigger for Uncached Execution Source: https://github.com/jcparkyn/phetch/blob/main/docs/docs/invoking-queries-manually.md The Trigger method forces a query to run with the provided argument, bypassing cache data. It does not share cached data with other components and is recommended for endpoints with side effects like PUT, POST, or DELETE operations. ```javascript query.Trigger(argument); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.