Sklep z kwiatami

Blog

  • Axios in Next.js: A Comprehensive Guide

    Next.js 14 introduced a new app structure, which provides a more streamlined and efficient way of building applications. In this article, we will explore how to use Axios, a popular JavaScript library for making HTTP requests, in a Next.js 14 project with the new app structure.

    Setting Up Axios in Next.js 14

    To use Axios in a Next.js 14 project, you need to install it first. Run the following command in your terminal:

    npm install axios

    Once installed, you can import Axios in your Next.js pages or components. However, to make Axios available throughout your application, you can create a separate module for it.

    Create a new file lib/axios.js with the following content:

    import axios from 'axios';
    
    const api = axios.create({
      baseURL: 'https://api.example.com', // Replace with your API base URL
    });
    
    export default api;

    This will create a new instance of Axios with a base URL for your API.

    Using Axios in Next.js Pages

    To use Axios in a Next.js page, you can import the api instance from the lib/axios.js file. Here’s an example of how to use Axios in a page:

    // app/page.js
    import api from '../lib/axios';
    
    export async function Page() {
      const response = await api.get('/data');
      const data = response.data;
    
      return (
        <div>
          <h1>Data from API</h1>
          <ul>
            {data.map((item) => (
              <li key={item.id}>{item.name}</li>
            ))}
          </ul>
        </div>
      );
    }
    
    export default Page;

    In this example, we’re using Axios to fetch data from the API and render it on the page.

    Using Axios with Server Components

    One of the new features in Next.js 14 is server components, which allow you to render components on the server-side. To use Axios with server components, you can use the fetch hook provided by Next.js.

    Here’s an example of how to use Axios with server components:

    // app/page/server.js
    import { fetch } from 'next/dynamic';
    import api from '../../lib/axios';
    
    export async function Page() {
      const response = await api.get('/data');
      const data = response.data;
    
      return (
        <div>
          <h1>Data from API</h1>
          <ul>
            {data.map((item) => (
              <li key={item.id}>{item.name}</li>
            ))}
          </ul>
        </div>
      );
    }
    
    export default Page;

    However, if you want to use the fetch hook provided by Next.js, you can do so by importing it dynamically:

    // app/page/server.js
    import dynamic from 'next/dynamic';
    const fetch = dynamic(() => import('next/fetch'), { ssr: true });
    
    export async function Page() {
      const response = await fetch('/api/data');
      const data = await response.json();
    
      return (
        <div>
          <h1>Data from API</h1>
          <ul>
            {data.map((item) => (
              <li key={item.id}>{item.name}</li>
            ))}
          </ul>
        </div>
      );
    }
    
    export default Page;

    Handling Errors with Axios

    When using Axios, it’s essential to handle errors that may occur during the request. You can use the try-catch block to catch any errors that may occur:

    // app/page.js
    import api from '../lib/axios';
    
    export async function Page() {
      try {
        const response = await api.get('/data');
        const data = response.data;
    
        return (
          <div>
            <h1>Data from API</h1>
            <ul>
              {data.map((item) => (
                <li key={item.id}>{item.name}</li>
              ))}
            </ul>
          </div>
        );
      } catch (error) {
        if (axios.isAxiosError(error)) {
          return (
            <div>
              <h1>Error: {error.message}</h1>
            </div>
          );
        } else {
          throw error;
        }
      }
    }
    
    export default Page;

    In this example, we’re using the try-catch block to catch any errors that may occur during the request. If the error is an Axios error, we’re rendering an error message on the page. Otherwise, we’re re-throwing the error.

    Conclusion

    In this article, we’ve explored how to use Axios in a Next.js 14 project with the new app structure. We’ve covered setting up Axios, using Axios in Next.js pages, using Axios with server components, and handling errors with Axios. By following these steps, you can easily integrate Axios into your Next.js project and start making API requests.

  • Simple Debounce Input in React

    n this article, we will explore how to create a simple debounce input in React using the use-debounce package. Debouncing is a technique used to limit the number of API requests made by an application, thereby improving performance and reducing server load.

    What is Debouncing?


    Debouncing is a programming technique that prevents a function from being called too many times in a short period of time. In the context of a search input, debouncing ensures that the API is not called on every keystroke, but rather after a certain delay, allowing the user to finish typing before making a request.

    Creating a Debounced Input in React


    To create a debounced input in React, we will use the use-debounce package. First, install the package using npm or yarn:

    npm install use-debounce

    Next, create a new React component for the input field:

    import React, { useState } from 'react';
    import { useDebounce } from 'use-debounce';
    
    const DebouncedInput = () => {
      const [searchTerm, setSearchTerm] = useState('');
      const debouncedSearchTerm = useDebounce(searchTerm, 500);
    
      const handleSearch = async () => {
        // Make API request here
        console.log('Searching for:', debouncedSearchTerm);
      };
    
      const handleChange = (event) => {
        setSearchTerm(event.target.value);
      };
    
      return (
        <div>
          <input
            type="search"
            value={searchTerm}
            onChange={handleChange}
            placeholder="Search"
          />
          <button onClick={handleSearch}>Search</button>
        </div>
      );
    };
    
    export default DebouncedInput;

    In this example, we use the useState hook to store the search term and the useDebounce hook to debounce the search term by 500 milliseconds. We then use the debounced search term to make the API request when the user clicks the search button.

    How Debouncing Works


    When the user types in the input field, the handleChange function is called on every keystroke, updating the searchTerm state. The useDebounce hook then debounces the searchTerm state by 500 milliseconds, creating a new debounced value that is only updated after the delay.

    When the user clicks the search button, the handleSearch function is called with the debounced search term. Since the debounced value is only updated after the delay, the API request is only made after the user has finished typing.

    Benefits of Debouncing


    Debouncing provides several benefits, including:

    • Reduced server load: By limiting the number of API requests, debouncing reduces the load on the server, improving performance and reducing the risk of errors.
    • Improved user experience: Debouncing ensures that the user is not subjected to a flood of API requests, improving the overall user experience.

    In conclusion, debouncing is a simple yet effective technique for improving the performance and user experience of a React application. By using the use-debounce package, you can easily create a debounced input field that limits API requests and improves the overall performance of your application.

  • Understanding the Difference Between „??” and „||” Operators

    JavaScript is a versatile and widely-used programming language, known for its concise syntax and powerful features. Two of its notable operators are the nullish coalescing operator (??) and the logical OR operator (||). While they may seem similar, they serve distinct purposes and have different behaviors. In this article, we’ll delve into the differences between these two operators and explore their use cases.

    How Work „??” (Nullish Coalescing Operator)?

    The nullish coalescing operator (??) is a binary operator that returns the first operand if it’s not null or undefined, and the second operand if it’s null or undefined. It’s a shorthand way to provide a default value when working with nullable or undefined variables.

    const name = null;
    const fullName = name ?? 'Unknown';
    console.log(fullName); // Output: Unknown

    What is the Logical OR Operator (||)?

    The logical OR operator (||) is a binary operator that returns the first truthy value it encounters. If the first operand is falsy, it returns the second operand.

    const name = '';
    const fullName = name || 'Unknown';
    console.log(fullName); // Output: Unknown

    Key Differences Between ?? and ||

    While both operators can be used to provide a default value, the key differences lie in their behavior:

    • Null and undefined values?? only returns the second operand if the first operand is null or undefined. In contrast, || returns the second operand if the first operand is falsy (e.g., empty string, 0, false).
    • Falsy values|| treats falsy values as „false” and returns the second operand. ?? doesn’t consider falsy values as „false” and returns the first operand if it’s not null or undefined.
    const name = '';
    const fullName1 = name ?? 'Unknown';
    console.log(fullName1); // Output: ''
    
    const fullName2 = name || 'Unknown';
    console.log(fullName2); // Output: Unknown

    Use Cases for ?? and ||

    • Use ?? when working with nullable or undefined values?? is ideal when you need to provide a default value for variables that might be null or undefined.
    • Use || when working with falsy values|| is suitable when you need to provide a default value for variables that might be falsy (e.g., empty string, 0, false).
    // Using ?? with nullable values
    const user = { name: null, age: 25 };
    const fullName = user.name ?? 'Unknown';
    console.log(fullName); // Output: Unknown
    
    // Using || with falsy values
    const name = '';
    const fullName = name || 'Unknown';
    console.log(fullName); // Output: Unknown

    Conclusion

    In conclusion, while both ?? and || can be used to provide a default value, they have distinct behaviors and use cases. Understanding the differences between these two operators will help you write more concise and readable JavaScript code.