1. Documentation
    2. Concept
    3. Content Declaration
    4. Function Fetching

    Function Fetching

    Function Declarations

    Intlayer allows you to declare content functions in your content modules, which can be either synchronous or asynchronous. When the application builds, Intlayer executes these functions to obtain the function's result. The return value must be a JSON object or a simple value like a string or number.

    Here's an example of a simple synchronous function fetching content:

    typescript
    1import type { DeclarationContent } from "intlayer"; 2 3const functionContent = { 4 key: "function_content", 5 content: { 6 text: () => "This is the content rendered by a function", 7 }, 8} satisfies DeclarationContent; 9 10export default functionContent;

    In this example, the text key contains a function that returns a string. This content can be rendered in your React components using Intlayer's interpreter packages like react-intlayer.

    Asynchronous Function Fetching

    In addition to synchronous functions, Intlayer supports asynchronous functions, allowing you to fetch data from external sources or simulate data retrieval with mock data.

    Below is an example of an asynchronous function that simulates a server fetch:

    typescript
    1import { setTimeout } from "node:timers/promises"; 2import type { DeclarationContent } from "intlayer"; 3 4const fakeFetch = async (): Promise<string> => { 5 // Wait for 200ms to simulate a fetch from the server 6 return await setTimeout(200).then( 7 () => "This is the content fetched from the server" 8 ); 9}; 10 11const asyncFunctionContent = { 12 key: "async_function", 13 content: { text: fakeFetch }, 14} satisfies DeclarationContent; 15 16export default asyncFunctionContent;

    In this case, the fakeFetch function mimics a delay to simulate server response time. Intlayer executes the asynchronous function and uses the result as the content for the text key.

    Using Function-Based Content in React Components

    To use function-based content in a React component, you need to import useIntlayer from react-intlayer and call it with the content ID to retrieve the content. Here's an example:

    javascript
    1import { useIntlayer } from "react-intlayer"; 2 3const MyComponent = () => { 4 const functionContent = useIntlayer("function_content"); 5 const asyncFunctionContent = useIntlayer("async_function_content"); 6 7 return ( 8 <div> 9 <p>{functionContent.text}</p> 10 {/* Output: This is the content rendered by a function */} 11 <p>{asyncFunctionContent.text}</p> 12 {/* Output: This is the content fetched from the server */} 13 </div> 14 ); 15}; 16 17export default MyComponent;

    If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.

    GitHub link to the documentation

    On this page