# Basic concepts ## APIs ### What are APIs? APIs (Application Programming Interfaces) are like messengers that allow different applications to communicate and exchange information with each other. Think of them as a set of rules that facilitate communication between different systems, like a common language that computers understand. In the context of Wized, APIs allow you to connect your Webflow project to external services, such as databases, payment gateways, email delivery platforms, and more. This gives you the ability to access functionality and data that is not directly available in Wized, extending the capabilities of your web application. ### Why are APIs important? APIs are fundamental to developing modern web applications, as they allow you to: - **Save time and resources:** Instead of developing all the functionalities from scratch, you can take advantage of the work of other developers and companies that offer ready-to-use APIs. - **Enrich your app:** APIs allow you to add advanced and custom features to your app, such as online payments, email notifications, interactive maps, social media integration, and more. - **Access real-time data:** You can obtain up-to-date information from external services, such as product prices, news, sports scores, or any other type of data relevant to your application. - **Create automated workflows:** You can set up actions that trigger automatically in response to specific events, such as sending a welcome email when a new user registers or updating data in an external database. ### How do APIs work in Wized? Wized allows you to interact with external APIs through **API requests**. These requests are like messages you send to the API, specifying what information you need or what action you want to perform. The API processes your request and responds to you with the requested data or with a confirmation or error message. To set up an API request in Wized, you need to set up the following: - **Endpoint:** The specific web address of the service you want to access (for example, ). - **HTTP Method:** The type of action you want to perform (GET to get information, POST to send data, etc.). - **Headers (optional):** Additional information about your request, such as the type of data you expect to receive or authentication credentials. - **Body (optional):** The data you want to send to the API, usually in JSON format. ### How to read API documentation and use it in Wized? Each API has its own documentation explaining how to interact with it. When reading the documentation, pay attention to: - **Available Endpoints:** Identify the different routes or endpoints that the API offers and what type of information you can obtain or send through each one. - **Allowed HTTP Methods:** Check which HTTP methods (GET, POST, etc.) you can use for each endpoint. - **Parameters and Body:** Determines which query parameters or data in the body you should include in your requests to obtain the desired results. - **Required Headers:** Some APIs require specific headers for authentication or to indicate the format of the data. - **Response Structure:** Understand how the API returns information, usually in JSON format, so you can process it correctly in Wized. # DOM (Document Object Model) The DOM is a tree-like representation of the structure of a web page. In Wized, you can use JavaScript to interact with the DOM, allowing you to modify page elements, add or remove content, and respond to user events dynamically. # JSON (JavaScript Object Notation) JSON is a lightweight format for exchanging data between different systems. At Wized, JSON is widely used to represent structured data, such as the results of API requests or information stored in the database. # Reactivity Responsiveness is one of the core pillars of Wized, allowing you to create web applications that feel alive and respond immediately to changes in data and user interactions. ## What is reactivity? In simple terms, reactivity means that your app updates automatically without the need to reload the entire page. Imagine you are viewing a list of products in an online store, and you apply a filter to show only the items on sale. In a reactive app, the list would instantly update to show only the filtered products, without you having to wait for the page to reload. ## Why is reactivity important in Wized? Responsiveness is essential to creating a fluid and modern user experience. By eliminating page reloads and updating only the necessary parts of the interface, Wized allows you to: - **Improve your app’s speed and performance:** Real-time updates make your website feel faster and more responsive, improving the overall user experience. - **Create more dynamic and engaging interactions:** Elements on your page can instantly change and adapt to user actions, such as clicking a button, selecting an option from a menu, or submitting a form. - **Display up-to-date information in real time:** You can integrate data from external APIs or your own backend to display up-to-date information in real time, such as product prices, notifications, or search results. ## How does reactivity work in Wized? Wized constantly monitors the state of your application, including the value of variables, cookies, API responses, and other relevant data. Whenever a change occurs in any of this data, Wized automatically re-evaluates all conditions associated with your element configurations. If a condition changes, Wized instantly updates the appearance or behavior of the corresponding element, without the need to reload the page. ## JSON (JavaScript Object Notetion) JSON is a lightweight format for exchanging data between different systems. It plays a crucial role in interoperability, allowing Wized to communicate seamlessly with various APIs and services. At Wized, JSON is widely used to represent structured data, such as the results of API requests or information stored in the database. ## DOM (Document Object Model) The DOM is a tree-like representation of the structure of a web page. In Wized, you can use JavaScript to interact with the DOM, which is essential for creating engaging and dynamic user interfaces. This allows you to modify page elements, add or remove content, and respond to user events in real-time. ## Return In Wized, the return keyword is required for every action that needs to return a value. This value can be the result of a validation, the response from an API, or any other data necessary for the action to work correctly. Proper use of `return` is key to the flow logic of applications in Wized. For example, if you want to change the color of an element, you must use return followed by the color you want (in hexadecimal or text). ## Null In JavaScript, null represents the intentional absence of any value. In Wized, you can use null to indicate that a variable or property has no value assigned. ## Undefined In JavaScript, undefined indicates that a variable has been declared but no value has been assigned to it. In Wized, you might encounter undefined when accessing properties of objects that don't exist or when using variables that haven't been initialized. Handling undefined appropriately also helps to prevent errors during program execution. ## True and False `true` and `false` are the two boolean values in JavaScript, representing truth and falsity, respectively. In Wized, you can use these values in conditionals and other logical expressions to control the execution flow of your application. ::: tip Example **Example of using boolean values in a conditional statement:** ```javascript let userLoggedIn = true; if (userLoggedIn) { console.log('Welcome back!'); } else { console.log('Please log in.'); } ``` ::: ## If...else The `if...else` structure is a method to implement conditional statements in JavaScript. In Wized, you can use `if...else` to perform different actions depending on whether a condition is met or not. ## Logical Operators (&&, ||, !) Logical operators are used to combine or negate boolean expressions. In Wized, you can use `&&` (AND), `||` (OR), and `!` (NOT) to create more complex conditions and control the flow of your logic precisely. ::: tip Example **Example of using logical operators:** ```javascript let isAdmin = false; let isUser = true; if (isAdmin || isUser) { console.log('Access granted'); } else { console.log('Access denied'); } ``` ::: ## Ternary Operator (? : ) The ternary operator is a shorthand way of writing an `if...else` statement on a single line. In Wized, you can use the ternary operator to assign a value to a variable based on a condition. ::: tip Example **Example of using the ternary operator:** ```javascript let age = 18; let canVote = age >= 18 ? 'You can vote' : 'You cannot vote'; console.log(canVote); ``` ::: ## Wized attributes In your Webflow-powered website, you need to add custom HTML attributes with the `wized` key and the value you want (e.g., `wized="my_button"`). Esto permite a Wized reconocer y utilizar dicho elemento dentro del configurador. > **Note**: All elements on your website are visible in the Wized configurator, but only those with the `wized` attribute can be used to create features. ## Wized-cloak The `wized-cloak` attribute is used to hide UI elements until Wized has finished loading and rendering the page. This prevents users from seeing raw content or flashing elements while the application is initializing. ## Wized-loader The `wized-loader` attribute is used to display a loading indicator while Wized is processing an action or retrieving data from an API. This provides visual feedback to the user and improves the overall application experience. # Return In Wized, the `return` keyword is required for every action that needs to return a value. This value can be the result of a validation, the response from an API, or any other data you need for the action to work correctly. For example, if you want to change the color of an element, you must use return followed by the color you want (in hexadecimal or text). # Conditional logic Conditional logic allows you to take control of your Wized app and make it behave differently depending on the circumstances. It's like a set of rules that tells your website, "If this happens, do this." ## Why use conditional logic? Conditional logic allows you to create more personalized and dynamic user experiences. Some of the things you can achieve with it are: - **Show or hide elements:** Do you want a button to appear only for logged in users? Or an error message to be displayed only if a form field is empty? With conditional logic, you can control the visibility of elements based on different conditions. - **Personalize messages and styles:** Want to greet your users by name or show them relevant content based on their interests? Conditional logic lets you dynamically adapt the text and appearance of your website. - **Create dynamic workflows:** Do you want your app to respond differently based on user actions? For example, you can redirect users to different pages after filling out a form, or display a success or error message based on the result of an API request. - **Validate input data:** Ensure that users enter correct information into forms, such as valid email addresses or strong passwords. - **Handling API errors:** If a request to an external API fails, you can display a user-friendly error message or perform some alternative action. ## How does conditional logic work in Wized? Conditional logic applies to element **settings and** event-related **actions . In both cases, you use the Function Editor** to write JavaScript code that defines the conditions and actions to be performed. **Example of a workflow with conditional logic:** 1. **The user interacts with your site:** For example, clicks a button or submits a form. 2. **An event is triggered:** Wized detects the user interaction and triggers the corresponding event (for example, On Click or On Submit ). 3. **Condition is evaluated:** If you have configured a condition in the Function Editor for that event or configuration, Wized evaluates it at that time. 4. **Action is executed or configuration is applied:** If the condition is met ( true ), Wized executes the action associated with the event or applies the configuration to the element. If the condition is not met ( false ), the action or configuration is not executed. ## Example Imagine you have a registration form and you want to display an error message if the user enters a password that is too short. 1. **Settings:** In the "Set Visibility" setting of a text element that will display the error message, type the following condition in the Function Editor: ```JavaScript return i.password.value.length < 8; ``` This condition checks if the length of the password entered in the password field is less than 8 characters. If so, it returns true and the error message will be displayed. If the password is 8 or more characters long, it returns false and the error message will remain hidden. 1. **Event:** Associate the On Input event with the password input field. This will cause Wized to re-evaluate the condition every time the user types or deletes a character in the field, updating the error message visibility in real-time. # Cookies ## Introduction Cookies are small pieces of information that your website stores in your browser. They act as long-term memory, allowing you to remember important details about yourself and your preferences even after closing the page or the browser. ### Why use cookies? - **Personalization:** Cookies allow you to remember your name, language preferences, color theme choices, or other information that will help you have a more personalized experience on your website. - **Authentication:** Cookies are commonly used to store authentication tokens, allowing your application to remember that a user is logged in and keep them authenticated while navigating your site. - **Tracking and analysis:** You can use cookies to track user behavior on your website, collecting information about the pages they visit, the products they view, and other actions they take. This helps you better understand your users and optimize your site for a better experience. - **Shopping carts and similar functionalities:** Cookies are essential for temporarily storing information about a user's shopping cart, allowing them to add and remove products without losing their selection while browsing the site. ### Creating and Managing Cookies in the Data Store Panel ![cookie-section](cookie-section.png) In the Data Store Panel, you will find the "Cookies" section where you can: - **View existing cookies:** You will see a list of all the cookies you have created, along with their current values. - **Create new cookies:** Click the "+" button and define a unique name and lifetime for your cookie. - **Edit cookies:** Click on an existing cookie to edit its name or value. - **Delete cookies:** Click on the cookie you want to delete, then click the trash can icon to delete it. ### Cookie Settings Options ![cookie-settings](cookie-settings.png) - **Name:** Choose a descriptive name for your cookie. - **Lifetime:** Choose how long you want the cookie to remain stored in the user's browser: - **1 day, 7 days, 30 days, 1 year:** The cookie value will persist for the selected time period, even if the user closes the browser. - **Custom:** You can specify the exact number of days you want the cookie to remain active. Once you've created your cookies in the Data Store Panel, you can access and use them in the [Function Editor](../function-editor/basic-concepts.md) to create conditional logic, customize messages, control element visibility, and more. ### Cookies and the Function Editor To access the value of a cookie in the [Function Editor](../function-editor/basic-concepts.md), use the prefix `c` followed by the name of the cookie. For example, if you have a cookie named `preferredTheme`, you can access its value using `c.preferredTheme`. ### Cookies and Reactivity Like variables, cookies in Wized are reactive. This means that any change in their value, whether through an action or directly in the Data Storage Panel, will trigger an automatic update of the configurations of the elements that depend on them. - **Example:** Imagine that you have a button that, when clicked, changes the color theme of your website and stores the user's preference in a cookie named `preferredTheme`. You also have several elements on your page whose Set Style configurations depend on the value of this cookie. 1. **Event:** When the button is clicked 2. **Action:** Set Cookie to update the value of the `preferredTheme` cookie with the new theme selected by the user. 3. **Reactivity:** Wized detects the change in the cookie and re-evaluates the conditions of all Set Style configurations that depend on it. The styles of the elements will automatically update to reflect the new theme chosen by the user, without the need to reload the page! ## Variables vs. Cookies: - [**Variables:**](./variables) These are ideal for storing temporary data that you only need while the user interacts with your application on the currently selected page. Their value is lost when the page is reloaded or the browser is closed. - **Cookies:** These are perfect for storing information that you want to retain between sessions, such as user preferences, authentication data, or the contents of a shopping cart. Keep in mind that cookies can persist beyond the browsing session. # Forms ## Introduction Forms in Wized allow you to interact with your users and collect valuable information in a structured and accessible way. You can create contact forms, registration forms, surveys, or any other type of form you need for your web application. Additionally, forms in Wized enhance the user experience by allowing submission with just a press of the “Enter” key. ### How do Forms work in Wized? A Form in Wized is a group of input fields (inputs, checkboxes, radio buttons, etc.) wrapped in a "Form" element. In order for Wized to interact with it, you must assign the `wized` attribute to the Form element and make sure that each input field has a descriptive name in its Webflow settings. Once connected, Wized groups all the form fields into an object, where each field becomes a property. You can access the values of each field using dot notation, for example: ```javascript f.form_name.field_name; // Access the values of each field using dot notation ``` ### Why use Forms in Wized? Forms allow you to: - **Collect information from your users:** Obtain contact information, preferences, comments, etc. - **Process data:** Send form data to an API or database for storage or further processing. - **Create dynamic interactions:** Use the information from the form to personalize the user experience, display success or error messages, or perform other actions in your application. ### How to create a Form in Wized? 1. **Design your Form in Webflow:** Create the form in Webflow with the input fields you need. 2. **Give your fields descriptive names:** In your Webflow settings, ensure that each input field has a descriptive and unique name. 3. **Add the wized attribute to the Form:** In Webflow, add the `wized` attribute to the main Form element. 4. **Access form values in Wized:** Once the user submits the form, you can access the values of each field in the Function Editor using dot notation. ### How to send the collected data? Forms use Webflow's default submit button to trigger data submission. 1. **Associate an On Submit event to the form:** In the Wized settings panel, select the form and associate the On Submit event . 2. **Perform Request action :** Within the On Submit event, select the Perform Request action and configure the API request you want to execute. 3. **Access the form data:** In the Function Editor of the request you want to execute, you can access the values of the form fields using the `f` [parameter](../function-editor/parameters#f-access-to-forms) and send them in the body of the request. ::: tip note that form field values are only available after the user has submitted the form. ::: ## Inputs vs Forms: Which to use? Both inputs and forms are essential elements for interacting with users and collecting data in your Wized app. However, it is important to understand their differences in order to choose the most appropriate option for each situation. ### Key behaviors - **Access to values in real time:** Inputs allow you to access their values in real time, which is useful for instant validations and dynamic interface updates. Forms, on the other hand, only provide access to their values after they are submitted. - **Field grouping:** Forms group multiple input fields into a single element, making them easier to manage and providing a more consistent user experience. Inputs, on the other hand, are handled individually. - **Native Validations:** Forms in Webflow offer basic native validations (such as requiring fields or checking email formats), while inputs require custom validations using conditional logic in Wized. - **Submit with Enter Key:** Forms can be submitted by pressing the Enter key, streamlining user interaction. Inputs require an additional element with an On Click configuration to trigger actions, such as sending data to an API. ### Recommendations for use - **Inputs:** Use these when you need to access values in real time to perform instant validations, dynamically update the interface, or create custom interactions based on the value of a single field. - **Forms:** Use them to collect structured information from your users, take advantage of native Webflow validations, and simplify the data submission process. # Data Store The Data Store serves as your central hub for monitoring and managing all the data within your Wized application. This panel provides a real-time overview of variables, cookies, URL parameters, API responses, and other critical elements that contribute to the logic and interactivity of your website. It is an essential resource for understanding the functionality of your application, troubleshooting issues, and crafting personalized and dynamic user experiences. Within the Data Store, you can: - **View the Current State of Your Application:** Monitor the values of variables, cookies, URL parameters, and other important data in real time as users interact with your site. - **Inspect API Responses:** Review the data received from API requests, including both headers and body content. - **Create and Manage Variables and Cookies:** Add, modify, or delete variables and cookies directly from the dashboard. - **Access Secrets:** Manage sensitive information by adding, modifying, or deleting secrets. - **Debug and Troubleshoot:** Utilize the Data Store to identify the causes of errors or unexpected behaviors in your application by observing how data changes in real time and its impact on the logic and configuration of your assets. ::: tip Note The data store is an indispensable tool for developing your web application in Wized, make sure to use it ::: # Inputs ## Introduction Inputs allow you to monitor and manage all the input fields on your page that you have connected with Wized. Here you can see their values in real time and use them to create dynamic and personalized interactions in your application. ### What will you find in the "Inputs" section? - **List of Inputs:** A complete listing of all the input fields on the currently selected page that have the wized attribute. These are the inputs that Wized recognizes and can interact with. - **Real-Time Values:** Next to each input, you will see its current value in real time. Each time the user interacts with the field, the value will automatically update in the dashboard. ### How to use Inputs in Wized? Inputs have a dual role in Wized: - **As a Data Source:** You can use the values of the inputs in the Function Editor to create custom conditions and logic. For example: - Show an error message if a field is empty: ```javascript // In the "Set Visibility" configuration of an error message element: return i.myField.trim() === '' ? true : false; // Checks if the field is empty ``` - Calculate the total of a purchase based on the selected quantity: ```javascript // In the "Set Text" configuration of an element that displays the total price: return `Total: $${(r.request_name.data.price * i.items).toFixed(2)}`; // Calculates the total formatted to two decimals ``` - **As Interactive Elements:** You can associate specific events with the inputs to trigger actions when the user interacts with them. Some common configurations for inputs are: - **On Change:** Triggered when the value of the input changes. - **On Input:** Triggered every time the user types or deletes a character in the input. - **Set Input Value:** Allows you to programmatically set the value of an input. ### How to send the collected data? 1. **Wized attribute on the button:** Ensure that the element acting as a button has the wized attribute with a unique value. 2. **Associate an On Click event:** In the Wized configuration panel, select the button and associate the On Click event. 3. **Perform the request action:** Within the On Click event, select the action to Perform Request and configure the API request you want to execute. 4. **Send the data in the request body:** In the Function Editor of the request that will be executed, you can access the input values using the [parameter](../function-editor/parameters#i-access-to-input-fields) `i` and send them in the request body. # Requests ## Introduction In the Requests section of the Wized data store, you will find a list of all the requests you have created in your project, each identifiable by its name. This section allows you to manage and test the requests to ensure they execute correctly and return the expected information. ## Execute Requests To test any request, simply locate it in the list and press the "play" button. This will execute the request and display the results, making it easier to verify that the configuration and returned data are correct. ## Details of Each Request Each request includes two main pieces of information that you can use in the Function Editor to create custom logic: ### Result: - Contains the data received in response to the request. - If no data is received, the result will be an empty array: - Includes the response headers, which you can also use in the Function Editor. ### State: Displays the different statuses of the specific request, including: - `hasRequested`: Indicates if the request has been executed before. - `isRequesting`: Indicates if the request is currently executing. - `statusText`: Text indicating the result of the request, e.g., success. - `status`: The HTTP status code returned, such as 200 for success. - `ok`: Returns true or false, indicating whether the request was successful (returns true if the HTTP code is in the range of 200-299). :::tip Note This result and the state data for each request are accessible in the Function Editor, where you can use them to build any type of logic that needs to interact with the data in a request, such as checking if information was received, handling errors, or conditioning the execution of other functions based on the results of a request. ::: # Secrets ## Introduction “Secrets” in Wized allow you to securely store sensitive information such as API keys, access tokens, and other data that you don’t want to expose directly in your application code. ### Why use Secrets? - **Security:** By storing your API keys and other sensitive data in Secrets, you prevent them from being visible in your application's source code, reducing the risk of leaks and unauthorized access. - **Requests via Wized Server:** When you use a Secret in an API request, the request is executed through our servers instead of directly from the user's browser. This adds an extra layer of security, especially for APIs that only accept requests from servers. - **Encryption:** Secrets are stored encrypted in our database, ensuring that only you, as the project owner, can access their true value. ### What kind of information should I store in Secrets? - **API Keys:** API keys are unique credentials that allow you to access external services, such as databases, third-party APIs, or payment platforms. Storing them in Secrets is essential to protect them from potential leaks. - **Other Authentication Secrets:** If your app uses other types of authentication credentials to access external services, such as access tokens or app passwords, you can also store those in Secrets. **Important!** Secrets are designed exclusively for storing API keys and other sensitive data related to authentication for external services. Please do not store your users' personal information here, such as names, emails, or account passwords, or authentication tokens generated upon login. Authentication tokens are temporary credentials that allow users to access protected areas of your application after logging in. These tokens are typically stored in cookies. ### Creating a Secret 1. **Access the Data Store Panel:** Click on the "Data Store" tab in the left navigation bar of the Configurator. 2. **Go to the "Secrets" section:** You will find a list of the secrets you have previously created. 3. **Click the "+" button:** A form will open to create a new secret. 4. **Fill in the fields:** - **Name:** Choose a descriptive name for your secret (for example, "api_key_stripe"). - **Value:** Enter the value of your API key or other sensitive data. 5. **Save the secret:** Click the "Save" button to encrypt and store the secret securely. ### Using a Secret To use a secret in an API request, simply access its value in the Function Editor using the s prefix followed by the secret name. For example: ```JavaScript // In the "Headers" configuration of an API request: return { return `Bearer ${s.my_secret_token}` }; ``` # Variables ## Introduction In Wized, variables serve as temporary containers that allow you to store and manage specific information. You can store various data types, including text, numbers, booleans (true or false), objects, and arrays (lists). These variables enable you to access and utilize the information across different sections of your application, offering significant flexibility for creating dynamic and personalized interactions. ### Why Use Variables? - **Display Dynamic Information:** Utilize variables to present custom content on your website, such as a user's name, the outcome of a calculation, or data retrieved from an API. - **Control Application Behavior:** Variables empower you to make decisions and execute different actions based on their values. For instance, you can show or hide elements, alter styles, or redirect users to various pages depending on a variable's state. - **Simplify Logic:** Storing information in variables helps you avoid code repetition, making your logic clearer and easier to maintain. ### Creating and managing variables in the Data Store Panel ![variables-section](variables-section.png) In the Data Store Panel, you will find the "Variables" section where you can: - **View existing variables:** You'll see a list of all the variables you've created, along with their current values. - **Create new variables:** Click the "+" button and define their name and initial value using the Function Editor. - **Modify variables:** Click an existing variable to edit its name or value. - **Delete variables:** Click on the variable you want to delete and then the trash can icon to delete it. ### Variable Configuration Options ![variable-settings](variable-settings.png) - **Name:** Choose a clear name for your variable so you can easily identify it later. For example, if your variable stores the username, you might call it `userName`. - **Initial Value:** Define the initial value of the variable using the Function Editor. You can use any data available in Wized, such as cookies, API responses, or user input. - **Persistence:** - **None:** The value of the variable will be lost upon reloading the page (default). - **Session Storage:** The value of the variable will persist during the user's session, even if they navigate to other pages within your application. This value will be removed when the tab or browser is closed. For example, if you store the shopping cart value, it will remain available as long as the tab is open. - **Local Storage:** The value of the variable will persist even after the user closes the browser, allowing information to be remembered between sessions. - **Computed:** If you check this option, the value of the variable will be automatically recalculated whenever any of its dependencies (other data used in its initial value) change. This is useful for creating variables that depend on other data and need to be updated in real-time. ### Variables and the Function Editor Once you've created your variables in the Data Store Panel, you can access and use them in the Function Editor to create conditional logic, perform calculations, display dynamic information, and more. #### Accessing Variables in the Function Editor To access the value of a variable in the Function Editor, use the v prefix followed by the variable name. For example, if you have a variable named username , you can access its value using v.username . #### Examples of using variables in the Function Editor - **Display a custom welcome message:** ```JavaScript // In the "Set Text" configuration of a text element: return `Welcome, ${v.username}!`; ``` - **Calculate the total price of a shopping cart:** ```JavaScript // In the "Set Text" configuration of an item that displays the total price: let total = 0; for (const product of v.cart) { total += product.price * product.quantity; } return `Total: $${total.toFixed(2)}`; ``` - **Controlling the visibility of an element:** ```JavaScript // In the "Set Visibility" configuration of an element: return v.showElement; // Show the element if v.showElement is true, hide it if false ``` ## Variables and Reactivity Variables in Wized are reactive, meaning that any change in their value will trigger an automatic update of events and configurations of elements that depend on them. This allows you to create dynamic and responsive user interfaces without the need to reload the page. - **Example:** Imagine you have a button that, when clicked, increments a counter stored in a variable called v.clickCount . You also have a text element that displays the value of this counter. 1. **Event:** On Click on the button 2. **Action:** Set Variable to increment the counter: v.contadorClics += 1; 3. **Configuration:** Set Text on the text element, with the return value `Clicks: ${v.contadorClics}` ; Every time the user clicks the button, the event will fire, the v.ClickCount variable will increment, and the element's text will automatically update to reflect the new value, all in real time! # Configuration Types ## Introduction In Wized, **single settings** are configurations that can only be applied once per element. This limitation helps prevent value overwriting, thereby reducing the risk of potential failures or inconsistencies in your application. Conversely, **multiple settings** can be applied repeatedly to an element without the risk of interference. This feature allows you to add as many values as needed while ensuring the system remains flexible and stable. # Set Class The Set Class feature allows you to dynamically manage CSS classes for elements, enabling efficient control over their appearance and behavior based on specific conditions. ## How does it work? 1. **Select Element:** Begin by choosing an element in your website layout where you wish to apply the Set Class settings. 2. **Apply the Set Class setting:** Go to the "Settings" tab of the elements panel and select the Set Class configuration. 3. **Enter class name:** Input the exact name of the CSS class you want to add or remove from the element. 4. **Define the condition in the Function Editor:** Use the Function Editor to specify the condition that will determine whether the class is added or removed. This condition should return a boolean value (true or false). ::: warning Note - **The class must exist in Webflow:** Ensure that the CSS class you specify in the Set Class configuration is defined in your Webflow project. Otherwise, you will not see visual changes when applying or removing the class. - **Combo classes:** If your element already has a base class in Webflow (e.g., "button"), adding a new class with Set Class (e.g., "highlight") will create a "combo class" (e.g., "highlight button"). Make sure that the styles for the combo class are set up correctly in Webflow to achieve the desired effect. ::: ## Advantages of Set Class - **Style Reuse:** You can define complex styles in Webflow and easily apply or remove them using Set Class. - **Organization and Clarity:** By using CSS classes, you keep your code more organized and easier to understand, especially in large projects with many elements and styles. - **Flexibility:** You can combine Set Class with other settings and configurations to create dynamic and customized interactions, such as animations, appearance changes, or hover effects. This allows you to create more engaging and unique user experiences. ## Practical Example For example, you have a button that you want to highlight only if the user is logged in. You can achieve this like this: 1. **In Webflow, create a CSS class named 'highlight':** Add the styles you want to apply to the button (for example, a different background color). 2. **In Wized, select the button and apply the Set Class setting.** 3. **In the "Class Name" field, type "highlight."** 4. **In the Function Editor, type the following condition:** ```javascript // Add the "highlight" class if the user is logged in return c.loggedInUser; ``` Done! Now, when the user logs in, the "highlight" class will be added to the button, changing its appearance according to the styles you defined in Webflow. If the user logs out, the class will be removed and the button will return to its original style. # Set HTML Attribute The **Set HTML Attribute** action in Wized enables you to modify the value of any HTML attribute of an element efficiently. ## How It Works 1. **Select Element:** Start by choosing the element in the element panel to which you wish to apply the settings. 2. **Apply the Set HTML Attribute Setting:** Navigate to the **Settings** tab in the properties panel and select the **Set HTML Attribute** action. 3. **Specify the Attribute Key:** Input the name of the HTML attribute you intend to modify (for example, `src`, `href`, `class`, etc.). 4. **Define the Value in the Function Editor:** Utilize the Function Editor to specify the new value for the attribute. You can incorporate any data available in Wized, such as variables, cookies, API responses, or values from other inputs. 5. **Add Conditions (Optional):** If desired, you can include a condition in the Function Editor to modify the attribute only under specific circumstances. ## Remove an HTML Attribute To remove an attribute from an element, simply return a `null` or `undefined` value from the function in the Function Editor. ## Examples - **Change a Product Image:** - **Attribute:** `src` - **In the Function Editor, enter:** ```javascript return r.getProduct.data.imageUrl; // Retrieves the image URL from the API response ``` - **Update a Button Link:** - **Attribute:** `href` - **In the Function Editor, enter:** ```javascript return v.destinationPage; // Provides the URL stored in a variable ``` - **Enable or Disable an Input:** - **Attribute:** `disabled` - **In the Function Editor, enter:** ```javascript return !v.formularioValido; // Disables the input if the form is invalid ``` - **Show or Hide an Element Using a Custom Data-\* Attribute:** - **Attribute:** `data-visible` - **In the Function Editor, enter:** ```javascript return c.usuarioPremium ? 'true' : 'false'; // Displays the item only if the user is a premium member ``` # Set Style The Set Style configuration allows you to dynamically modify any CSS property of an element, providing you with the flexibility to create custom and interactive user interfaces. Change colors, sizes, positions, and any other visual aspect of your elements in response to [events](../../../global-events/index.md), [data](../../../data-store/index.md), or [conditional logic](../../../conditional-logic/index.md). ## Why use Set Style? - **Visual interactivity:** Create visual effects and interactions that respond to user actions or changes in your application. - **Dynamic adaptation:** Modify the appearance of your elements based on real-time data, such as product availability, user role, or information from an external API. - **Custom personalization:** Adjust the style of your website for each user or situation, creating a unique experience. ## How does it work? 1. **Select Element:** Choose the element in your Webflow design to which you want to apply the configuration. 2. **Apply the Set Style configuration:** In the **Settings** tab, select the Set Style configuration. 3. **Choose CSS property:** Use the dropdown menu to select the CSS property you want to modify (e.g., color, background-color, width, height, etc.). 4. **Set the value in the Function Editor:** Use the Function Editor to specify the new value for the CSS property. You can use any data available in Wized. > **Note:** Ensure that the value you return is valid for the selected CSS property. For example: ```javascript return '#ff0000'; // for color return '10px'; // for size return 'block'; // for display ``` 5. **Add conditions (optional):** If you want the element's style to change only under certain circumstances, you can add a condition in the Function Editor. ## How to create seamless transitions While Set Style allows you to change the CSS properties of your elements dynamically, these changes happen instantly by default. To create smooth, animated transitions, you can combine Set Style with Webflow's CSS transitions. ### Steps to create smooth transitions 1. **Define transitions in Webflow:** - Select the element in Webflow to which you want to apply transitions. - Go to the "Effects" tab and choose the "Transitions" section. - Click the "+" button to add a new transition. - In the "Property" dropdown menu, select the CSS property you want to animate (e.g. background-color, width, opacity, etc.). - Choose the duration of the transition and the type of animation (ease-in-out, linear, etc.). You can use the predefined options or create a custom transition using the "Easing Editor". This editor allows you to specify how the transition progresses over time, providing various easing functions that control the acceleration and deceleration of the transition. - If you want to apply the same transition to all CSS properties of the element, you can select the "All Properties" option. 2. **Set Set Style to Wized:** - Set the Style to the CSS property you animated in Webflow. - In the Functions Editor, define the logic to change the CSS property value based on desired conditions. ### Example Imagine you have a button that changes color when a request ends. You can create a smooth transition like this: 1. **In Webflow:** - Select the button and go to the "Effects" section. - Add a transition for the background-color property with a duration of 0.3 seconds and an ease-in-out animation. 2. **In Wized:** - Select the button and apply the Set Style setting to the background-color property. - In the Functions Editor, type: ```javascript return r.request_name.hasRequested ? 'blue' : 'red'; // Change the background color based on whether the request has been made ``` ## Webflow interactions vs Wized set style Webflow native interactions allow you to add basic animations and transitions to enhance the user experience, such as changing colors on hover, showing or hiding elements on click, or creating more complex animations. Wized advances this interactivity by enabling you to create advanced conditional logic and connect your elements to external data, giving you greater flexibility and control to customize the user experience. ### When to use Wized instead of Webflow? Use Wized when: - You need conditional logic for interactions based on specific conditions, such as the value of a variable, the state of a cookie, or the response of an API. - You want to connect your site to external data, such as an API or database, to display dynamic content or personalize the user experience. - You are looking for greater flexibility and control over the behavior of your elements, allowing for the creation of complex and custom interactions beyond Webflow's native capabilities. --- ## Practical Examples 1. Change the background color of a button - **CSS Property:** background-color - In the Function Editor, type: ```JavaScript return 'red'; ``` 2. Show a progress bar - **CSS Property:** width - In the Function Editor, type: ```JavaScript return `${r.request_name.data.progress}%`; ``` 3. Change the color of a text according to the user's role: - **CSS Property:** color - In the Function Editor, type: ```JavaScript return r.getUserData.data.role === 'admin' ? 'gold': 'black'; ``` 4. Hide an item if no data is available: - **CSS Property:** display - In the Function Editor, type: ```JavaScript return r.getData.data.length > 0 ? 'block': 'none'; ``` # Add Parameter to Link The **Add Parameter to Link** setting allows you to add additional information to links on your website. This information is appended to the end of the URL in the form of **query parameters**, which are key-value pairs separated by question marks and ampersands. For example, if you have a link to a product page with the URL , you can add a query parameter called `id` with the value `12345` to indicate which specific product should be displayed: . ## How does it work? 1. **Select the element:** Choose the element from the elements panel in Webflow. Ensure that the element has a configured destination URL. 2. **Apply the Add Parameter to Link setting:** In the "Settings" tab of the properties panel, select the Add Parameter to Link action. 3. **Choose the parameter:** Use the dropdown menu to select the parameter you want to add to the link. Ensure that all parameters are correctly defined in the "Navigation" section of the Data Panel to avoid confusion. 4. **Define the value in the Function Editor:** Use the Function Editor to specify the value you want to assign to the parameter. You can use any available data, such as variables, cookies, API responses, or even the value of other inputs. 5. **Done!** When you click the link, the parameter and its value will be automatically added to the destination URL. On the destination page, you can access this value using `n.parameters.parameter_name` in the Function Editor. ## Why use Add Parameter to Link? - **Dynamic Detail Pages:** Pass the ID of a product, item, or other to load specific information about that product on the destination page. - **Filters and Searches:** Pass search criteria or filters through parameters to display relevant results on the next page. - **Campaign Tracking:** Add UTM parameters to your links to analyze traffic and performance of your marketing campaigns. - **Personalization:** Pass user information or preferences to personalize the content or functionality of the destination page. ## Practical Example Imagine you have a list of products on your website and want to redirect the user to a details page with specific information about that product when they click on it. You can achieve this as follows: 1. **In Webflow, create a link in the product card that points to the details page.** 2. **Apply the Add Parameter to Link setting.** 3. **Select the parameter `productId`** (make sure you have created it previously in the Data Panel). 4. **In the Function Editor, write:** ```javascript // Get the product ID from the rendered list return r.getProducts.data[v.i].id; // 'v.i' must correspond to the index of the product being clicked ``` ```javascript // Get the product ID return r.getProduct.data.id; ``` Now, when clicking on a product, the destination URL will include the `productId` parameter with the corresponding ID, allowing you to display the correct information on the details page. # Render List The Render List configuration allows you to display data lists in a structured way on your website. Whether you are fetching data from an API or using information stored in your application, Render List helps you display lists that automatically adapt to the number of available items. ## How does it work? 1. **Define the "template" item:** Design in Webflow how you want each item in the list to look. You can include text, images, buttons, and any other elements you need. 2. **Choose the "template" element:** Select the element (in the elements panel) that will act as the "template" for the list. This element will be duplicated by Wized as many times as necessary to display all items in your list. 3. **Provide the data:** In the Function Editor of the Render List configuration, you need to return an array (a list) of items. These items can come from an API request (for example, `r.getProducts.data.products`) ```javascript // Example of how to return a list of products from an API return r.getProducts.data.products; // Returns the list of products ``` 4. **Define an index variable:** Specify a variable (usually called i) to keep track of the position of each item in the list. This variable will be crucial for accessing the data of each individual item when customizing its content. Remember that each list must have a unique index to avoid potential errors. ::: warning Important If you want to render multiple lists on the same page at the same time, make sure to use a different index variable for each Render List action. ::: --- ## Design and organization Keep in mind that Wized handles the duplication and rendering of your list items, but the visual layout and organization of the list depend on how you have structured the container element in Webflow. Ensure that the design of your container element is flexible and adapts well to different amounts of content. ## Configure Each Item in the List Once the Render List action has been configured, each item in the list will be a copy of the "template item" designed in Webflow. To display dynamic information in each item and create a personalized experience, it is necessary to individually configure the child elements within the template. Imagine you have a list of products. You can use Render List to display a dynamic list of cards for each product, and then use [Set Text](./set-text) on another element within the card to show the name of each product in its respective card. ### Steps to Personalize Elements Within a List 1. **Ensure that Child Elements Include the [Wized Attribute](../../../getting-started/wized-attribute):** Remember that each element you wish to "personalize" must include the Wized attribute with a unique value for Wized to recognize it as an [Element](../../index). 2. **Check the Hierarchy:** The elements you wish to personalize must be direct children of the "template item" in the Webflow design structure. 3. **Select the Child Element in the Wized Elements Panel:** Select the child element you want to configure. 4. **Choose the Desired Configuration:** Apply the appropriate settings to what you want to do, such as [Set Text](./set-text), [Set Visibility](./set-visibility), [Set Style](../multi-use/set-style), etc. For example, if you want an element to change its visibility based on certain conditions, you can configure it using [Set Visibility](./set-visibility). 5. **Use the Index Variable in the Function Editor:** Within the Function Editor, use the index variable (for example, v.i) to access the corresponding data for each item in the list. ## The Importance of the Index Variable In the Render List action, you must choose a variable that will act as an index or iterator. This variable is essential for dynamically customizing each item in the list. Wized, recognizes this variable and uses it to iterate through the data list you provided, assigning a numeric value to each item (starting from 0). For example, if you have a list of products and choose the variable i as the index, Wized will assign the following values to each product: - First product: i = 0 - Second product: i = 1 - Third product: i = 2 - And so on... Then, when configuring the child elements within the list, you can use this index variable to access the data for each product. For example, if you want to display the name of each product in a text element, you could use the following expression in the Function Editor: ```javascript // Returns the name of the product corresponding to each item return r.getProducts.data[v.i].name; ``` ## Nested Rendering: Lists Within Lists Wized also allows rendering nested lists, which means lists within other lists. To do this, simply add a Render List configuration to a child element within the "template" element. Be sure to follow the steps mentioned earlier (Steps to customize elements within a list). ::: warning Note - Use a different index variable for each level of nesting. For example, use `v.i` for the main list and `v.j` for the nested list. - Access nested properties using the appropriate syntax. For example, `r.getProducts.data[v.i].categories[v.j].name`. ::: ### When to Use Nested Arrays? Nested arrays are useful for representing hierarchical relationships or grouping data in more complex ways. Some common examples include: - **Categories and Subcategories:** You can use a nested array to represent a list of categories, where each category contains an array of subcategories or products. - **Data Tables:** You can use a nested array to represent a data table, where each row is an array that contains the values of different columns. - **Option Trees:** You can use a nested array to represent an option tree, where each node in the tree contains an array of sub-nodes. ### Example: Display a list of categories and their products 1. **Structure in Webflow:** Create a main "template item" for the list of categories and, inside it, a child "template item" for the list of products in each category. 2. **Configuration in Wized:** - Applies Render List to the parent "template item", using the index variable v.i and returning the categories array . - Applies Render List to the child "template item", using the index variable v.j and returning categories[v.i].products . - Use Set Text or other settings on the nested list's child items to display information for each product (e.g. categories[v.i].products[v.j].name ). **Visual Example:** ``` [Main List] ├── [Item 1] │ ├── [Sub Item 1] │ └── [Sub Item 2] ├── [Item 2] │ └── [Sub Item 1] ``` --- ## Examples - **Show Product Name:** ```javascript // In the "Set Text" configuration for a text item within the list: return r.getProducts.data[vi].name; // Returns the name of the product at the index vi ``` - **Display an "Add to Cart" Button Only When Stock is Available:** ```javascript // In the "Set Visibility" configuration for a button within the list: return r.getProducts.data[vi].stock > 0; // Returns true if stock is greater than 0, otherwise false ``` > **Note**: If the index variable is not used in the function editor, the same configuration will apply to all items in the list, which will not allow displaying dynamic. # Set Form Values The **Set Form Values** setting allows you to simultaneously set values for multiple input fields within a form. This feature is particularly useful for pre-populating forms with existing information or dynamically updating multiple fields at once. ## How Does It Work? 1. **Select the Form**: In the Wized elements panel, click on the form that contains the input fields you wish to modify. 2. **Apply the Set Form Values Setting**: Navigate to the "Settings" tab in the properties panel and select the **Set Form Values** action. 3. **Define Values in the Function Editor**: Use the Function Editor to specify the values to be set in the form fields. Return an object where the keys correspond to the names of the input fields (as defined in Webflow), and the values are the new values you want to assign. ```javascript return { name: r.get_user.data.name || '', email: r.get_user.data.email || '', age: r.get_user.data.age || '', }; ``` 4. **Add Conditions (Optional)**: If you want to update the form values only under specific conditions, you can include a conditional statement in the Function Editor. ### Important Considerations - **Data Format**: Ensure that the values you provide in the object match the expected data types of each input field. For instance, if a field is of type "number," you must provide a numeric value. - **Field Names**: The keys in the object must exactly match the names of the input fields in your Webflow form. # **Set Input Value** The "Set Input Value" configuration allows you to dynamically and automatically set the value of an input field. You can pre-fill forms, display search results, or any other interaction that requires updating the value of an input. ## How it works 1. **Select the input:** In the Wized element panel, click on the input field you want to configure. 2. **Apply the Set Input Value configuration:** In the "Settings" tab of the properties panel, select Set Input Value. 3. **Define the value in the Function Editor:** Use the Function Editor to specify the value you want to set in the input field. You can use any data available in Wized, such as variables, cookies, API responses, or even the value of other inputs. For example, the code in the Function Editor would look like this: ```javascript return 'desired value'; // Sets the desired value in the input field ``` 4. **Add conditions (optional):** If you want the input's value to be updated only under certain circumstances, you can add a condition in the Function Editor. ## Practical Examples - **Pre-filling forms:** If you have user information stored in cookies or variables, or your DB, you can use "Set Input Value" to pre-fill form fields. - **Displaying search results:** When performing a search, this function can be used to show the search terms within an input field. This allows you to edit or refine your queries. - **Updating input fields based on other values:** You can use conditional logic in the Function Editor to update the value of an input based on other data from your application. # Set Text The **Set Text** functionality allows you to display dynamic text in an element on your website. You can customize welcome messages, show real-time information retrieved from an API, or create any other interactive text-based experience. ## How It Works 1. **Choose the type of text:** Select whether you want to display plain text, HTML, or Markdown. 2. **Define the content:** Use the Function Editor to specify the text that will be displayed in the element. Here you can: - **Use fixed values:** Write the text directly in quotes. - **Access dynamic data using:** Use Wized prefixes (c, v, i, f, r, n) to access cookies, variables, inputs, API responses, navigation data, and more. - **Create conditional logic:** Use if...else, ternary operators, and other JavaScript tools to customize the text based on different conditions. ## Practical Examples - **Display a personalized welcome message:** Before showing the code, we are checking if the user is logged in. If so, their name will be displayed; otherwise, a general greeting will be shown. ```javascript // If the user is logged in, show their name. Otherwise, show a general greeting. return c.userLoggedIn ? `Welcome back, ${r.get_user.data.name}.` : 'Hello.'; ``` - **Display the price of a product from an API:** ```javascript // Retrieves the price of a product from an API and formats it. return `${r.product_request.data.price.toFixed(2)}`; ``` - **Display a list of items in HTML format:** ```javascript // Generates an HTML list from an array of items. const listitems = v.myList.map((item) => `
  • ${item}
  • `).join(''); return `
      ${listitems}
    `; ``` - **Show an error message if a condition is not met:** ```javascript // Checks if an input field is empty and shows an error message if necessary. return i.name.value.trim() === '' ? 'Please enter your name.' : ''; ``` --- ::: tip Considerations - If you choose the HTML or Markdown format, ensure that the text is valid and properly structured. - Use the Results View in the Function Editor to test your code and verify that the text displays correctly, paying special attention to possible syntax errors in the code. ::: # Set Visibility The Set Visibility configuration allows you to dynamically show or hide elements of your website. ## How does it work? The Set Visibility feature applies to a specific element and uses a condition defined in the Function Editor to determine whether the element should be shown or hidden. - **Condition:** A JavaScript expression that Wized evaluates to decide whether to show or hide the element. Its result must be a boolean value (true or false). You can use any information available in your application, such as the value of a variable, the contents of a cookie, an API response, or the current page, to create flexible, custom conditions. - **Reactivity:** Wized constantly monitors the state of your application. If the condition associated with the Set Visibility feature changes, Wized automatically updates the visibility of the element in real time, without the need to reload the page. ## Practical Use Cases - **Show content only to authenticated users:** Hide items only for members or administrators until the user has successfully logged in. - **Customize welcome messages:** Display different welcome messages based on the user's name, location, or other preferences. - **Create dynamic forms:** Show or hide form fields based on user selections or information obtained from an API. - **Show error or success messages:** Hide messages until a specific condition is met, such as a successful form submission or an error response from an API. - **Create animation effects:** Combine Set Visibility with CSS transitions to achieve fade-in and fade-out effects for elements. ## Example: Display a Button Only for Administrators Imagine you have an "Edit Content" button that should only be visible to users with the admin role. You can achieve this as follows: 1. **Associate the Set Visibility feature with the button.** 2. **In the Function Editor, type the following condition:** ```javascript // Show the button only if the user's role is "admin" // r.getUserData.data.role retrieves the role of the current user from the user data object. return r.getUserData.data.role === 'admin'; // This condition returns true if the role is admin; otherwise, false. ``` # Elements Panel # Introduction This panel centralizes the management of each element of your Web Application. - **Hierarchical Listing:** Elements are organized in a tree based on their hierarchy in the Webflow page structure, making navigation and searching easier. - **Accessing Settings and Events:** Clicking on an item in the panel takes you to its settings panel, where you can: - Configure element behavior : Define how it will look and behave in different situations using settings like "Set Text", "Set Visibility", "Render List" and many more. - Add Events : Associate events such as "On Click", "On Change" or others to the element to trigger specific actions when the user interacts with it. ::: tip Note For more information about how this panel works, refer to [Elements events](../elements/events) and [settings](../elements/settings-overview) ::: # Element Events ## Introduction Element Events are the interactions that the user performs with your application, such as clicking on an element, entering a value in an input field, or submitting a form. Wized allows you to "listen" for these events and respond to them by executing specific actions. ## How does it work? ![event-tab](event-tab.png) 1. **Select the element:** In the Wized elements panel, click on the element to which you want to add this configuration. 2. **Associate the event:** Go to the "events" tab in the properties panel. 3. **Choose the event:** Use the dropdown menu to select the event you want to "listen" to. You can choose from a wide variety of standard JavaScript events, such as `click`, `submit`, `change`, `input`, `focus`, `blur`, `keydown`, etc. Check the full list. 4. **Select the action:** Choose the action you want Wized to perform when the selected event occurs. 5. **Configure the action:** Depending on the action you select, you will have different configuration options. For example, to **Make a Request**, you will need to specify the API request you want to execute. 6. **Add a condition (optional):** If you want the action to execute only under certain circumstances, you can add a condition in the Function Editor. This condition must return a boolean value (`true` or `false`). ## Available Actions Actions are tasks that Wized performs in response to an event. You can chain multiple actions to create custom and complex workflows. - **Modify Cookie:** Modifies the value of a cookie. - **Modify Variable:** Modifies the value of a variable. - **Custom Function:** Executes a custom JavaScript function to perform more advanced operations or interact with external APIs. - **Make a Request:** Executes a request to an API to fetch or send data. ## Managing Actions All actions within an event can be easily managed: - **Add New Actions:** Insert a new action at any position within the chain. - **Reorganize Actions:** Rearrange actions by dragging them to the desired order. This flexibility lets you define precise workflows, as each action executes sequentially after the previous one. - **Delete Actions:** Remove actions that are no longer needed. This level of control allows you to build complex and customized flows tailored to your application’s needs. ## **Reactivity in Wized** Wized has the ability to instantly react to changes in your application. Whenever any change in the state of your application is modified (for example, by changing the value of a variable or cookie or receiving a response from an API), Wized automatically re-evaluates all the conditions you have defined in your item settings. If the result of any condition changes, Wized instantly updates the appearance or behavior of the relevant elements, without requiring a page reload. ## Why are there no actions like "Set Text" or "Set Visibility"? The rationale behind this is [Wized's reactivity](../basic-concepts/reactivity#what-is-reactivity). Instead of having separate actions for every possible change to an element's appearance or behavior, Wized lets you define those settings directly on the elements, along with conditions that determine when they are applied. ### How does it work? 1. **Configure your elements:** Use the `Set Text`, `Set Visibility`, `Set Style`, etc. settings to specify how you want your elements to behave in different scenarios. 2. **Add conditional logic:** In the Function Editor, write the conditions that determine when these settings will be applied. You can use any data available in Wized, such as variables, cookies, or API responses. 3. **Wized does the rest:** Whenever an event occurs that modifies the state of the application, Wized automatically re-evaluates all the conditions associated with your elements' configurations. If a condition changes, the corresponding configuration is updated instantly. ### **Practical examples** - **Display a confirmation message when submitting a form:** - **Event:** On Submit in the form - **Action:** Set Variable to set a formSubmitted variable to true . - **Setting in another element (for example, a confirmation message):** Set Visibility with condition v.formularioEnviado . - **Refresh a product list by changing a filter:** - **Event:** On Change in a category dropdown menu - **Action:** Perform Request to obtain the products of the selected category. - **Setting on a list item:** Render List to display products obtained from the API. - **Validate an input field in real time:** - **Event:** On Input in an input field - **Action:** Custom Function to validate the entered value and display an error message if necessary. # Elements ## Introduction In Wized, elements designed in Webflow can be transformed into interactive components, enabling users to interact with features such as dynamic actions, user-triggered events, and customizable settings. Before exploring interactivity, it is important to understand how Wized interacts with the elements of your Webflow site. The [elements panel](../elements/elements-panel.md) centralizes the management of each element in the application, facilitating the organization and access to configurations and events. - **Hierarchical Listing:** Elements are organized in a tree according to their hierarchy in the Webflow page structure, making navigation and search easier. - **Access to Configurations and Events:** Clicking on an element in the panel takes you to its configuration panel, where you can: - **Configure Behavior:** Define how it will look and behave in different situations using settings such as "Set Text", "Set Visibility", "Render List", among others. - **Add Events:** Associate events such as "On Click", "On Change Event", or others to the element to trigger specific actions when the user interacts with it. ::: info information To enable Wized to effectively interact with an element on your website, you need to add the `wized` attribute in Webflow. ::: # Element Settings ## Introduction ![element-settings](element-settings-panel.png) Element settings serve as instructions for each component of your website. They dictate how an element will appear and behave under various conditions. You can configure an element with the following options: - **Show/Hide:** Manage the visibility of an element based on specific conditions, such as the user's role, variable values, or API responses. - **Change Text:** Dynamically update the content of a text element to display personalized information or relevant messages tailored to the user. - **Generate a List:** Create dynamic lists of items sourced from data, including products, blog posts, or search results. - **Modify Styles:** Adjust the color, size, position, or other CSS properties of an element to achieve desired visual effects and animations. - **Add or Remove Classes:** Apply or remove predefined CSS classes in Webflow to alter the appearance or behavior of an element. - **Modify HTML Attributes:** Change attributes such as `src` (for images), `href` (for links), or any other HTML attribute dynamically to meet application requirements. - **Add Parameters to Links:** Incorporate dynamic parameters into your link URLs, facilitating the transfer of information between pages or customizing the behavior of your application. ::: info Information By effectively utilizing these settings, you can enhance the interactivity and responsiveness of your website. ::: # Basic Concepts ## The keyword return The `return` keyword is essential in JavaScript functions. It indicates the value that the function should return at the end of its execution. ::: warning Important In Wized, you must **always include the** `return` keyword at the end of your functions in the Function Editor, even if it returns a boolean value, such as `true` or `false`. If you don't include `return`, your function will return `undefined`, which may result in errors or unexpected behavior in your application. ::: --- ## Dot Notation Dot notation is an effective and straightforward method for accessing specific properties within objects and arrays in JavaScript. ### How Does It Work? Consider your data as a tree structure, where each branch represents a property and each leaf corresponds to a value. Dot notation allows you to "navigate" this tree by specifying the path from the root to the desired leaf. For example, if you have a user object with properties like `name` and `email`, you can access these properties using dot notation as follows: ```javascript const user = { name: 'John Doe', // User's name email: 'john.doe@example.com', // User's email }; return user.name; // Returns 'John Doe' return user.email; // Returns 'john.doe@example.com' ``` Additionally, dot notation is not only used for objects but also for arrays. Here is an example of how to access a value within an array using dot notation: ```javascript const users = [ { name: 'John Doe', email: 'john.doe@example.com' }, { name: 'Jane Smith', email: 'jane.smith@example.com' }, ]; // Accessing the name of the first user return users[0].name; // Returns 'John Doe' // Accessing the email of the second user return users[1].email; // Returns 'jane.smith@example.com' ``` --- ## Operators and Expressions Operators are symbols used to perform calculations and comparisons in your JavaScript code. Below are the principal categories of operators you will encounter: ### Arithmetic Operators: These include `+`, `-`, `*`, `/`, and `%`, which perform addition, subtraction, multiplication, division, and modulus (remainder of division), respectively. ```JavaScript // Subtraction: Calculate remaining stock with variable let initialStock = v.initialStock; // stock variable let soldItems = 5; // fixed number of items sold return remainingStock = initialStock - soldItems; // subtract sold items from stock // Multiplication: Calculate interest on product price from API response let productPrice = 200; // fixed product price let interestRate = r.getInterest.data; // interest rate from an API request response return totalWithInterest = productPrice * interestRate; // multiply price by interest rate // Division: Calculate average score from a sum of scores let sumOfScores = v.totalScores; // total scores variable let numberOfTests = 4; // fixed number of tests return averageScore = sumOfScores / numberOfTests; // divide total scores by number of tests ``` ### Comparison Operators: These include `>`, `<`, `>=`, `<=`, `==`, `!=`, `===`, and `!==`. They are used to compare values, determining if one is greater than, less than, equal to, or not equal to another. ```JavaScript // Greater than (>): Check if total points exceed a threshold let totalPoints = v.totalPoints; // variable storing total points let pointsThreshold = 100; // fixed threshold value return exceedsThreshold = totalPoints > pointsThreshold; // true if totalPoints is greater than pointsThreshold // Greater than or equal to (>=): Check if cart total meets minimum for discount let cartTotal = v.cartTotal; // total value of items in the cart let minForDiscount = 50; // minimum cart total for discount return qualifiesForDiscount = cartTotal >= minForDiscount; // true if cartTotal is at least minForDiscount // Equal to (==): Check if user role matches required role (loose equality) let userRole = v.userRole; // user role variable let requiredRole = "admin"; // required role return isAdmin = userRole == requiredRole; // true if userRole loosely equals requiredRole // Strict not equal to (!==): Check if API response status differs from success let responseStatus = r.apiResponse.status; // response status from an API let successStatus = 200; // success status code return isError = responseStatus !== successStatus; // true if responseStatus is not equal to successStatus ``` ### Logical Operators: These include `&&` (AND), `||` (OR), and `!` (NOT). They are used to combine or negate boolean expressions. ```JavaScript // AND (&&): Check if user is logged in and has admin role let isLoggedIn = c.loggedIn; // boolean from cookie indicating login status let isAdmin = v.role === "admin"; // boolean check for admin role let canAccess = isLoggedIn && isAdmin; // true if both logged in and role is admin // OR (||): Check if product is in stock or if backorder is allowed let inStock = v.stock > 0; // boolean indicating if stock is available let allowBackorder = v.backorder; // boolean indicating if backorder is allowed let canPurchase = inStock || allowBackorder; // true if in stock or backorder allowed // NOT (!): Negate login status to check if user is not logged in let loggedIn = c.loggedIn; // boolean indicating login status let isGuest = !loggedIn; // true if user is not logged in // Combined example: Check if user is an admin and either logged in or has a valid session let role = v.role === "admin"; // boolean for admin role let loggedInStatus = c.loggedIn; // boolean for login status let validSession = v.session === "valid"; // boolean for valid session status let access = role && (loggedInStatus || validSession); // true if admin and (logged in OR has a valid session) ``` ### Assignment Operators: These operators allow you to assign a value to a variable or update its existing value: - `=`: Assigns a value to a variable. - `+=`: Adds a value to the current value of the variable. - `-=`: Subtracts a value from the current value of the variable. - `*=`: Multiplies the current value of the variable by a value. - `/=`: Divides the current value of the variable by a value. - `%=`: Calculates the modulus (remainder of division) of the current value of the variable by a value. ```JavaScript let counter = 0; counter += 1; // Increment the value of "counter" by 1 (it is now equal to 1) counter *= 2; // Multiply the value of "counter" by 2 (it now equals 2) ``` ## Conditionals (if...else) Conditionals allow you to execute different blocks of code depending on whether a condition is met or not. The basic structure of an if...else conditional is: ```JavaScript if (condition) { // Code to be executed if the condition is true } else { // Code to execute if the condition is false } ``` **Example** ```JavaScript // Example: Check if the user qualifies for a discount based on cart total let cartTotal = v.cartTotal; // variable storing the total value in the user's cart let discountThreshold = 50; // minimum cart total to qualify for a discount if (cartTotal >= discountThreshold) { // User qualifies for discount return "Congratulations! You qualify for a discount."; } else { // User does not qualify for discount return "Add more items to your cart to qualify for a discount."; } ``` ## Ternary operators The ternary operator is a shorthand way of writing a simple conditional on a single line. Its structure is: ```JavaScript condition ? valueIfTrue : valueIfFalse ``` **Example** ```JavaScript // Example: Check if the user qualifies for a discount using a ternary operator let cartTotal = v.cartTotal; // variable storing the total value in the user's cart let discountThreshold = 50; // minimum cart total to qualify for a discount // Ternary operator for discount qualification let message = cartTotal >= discountThreshold ? "Congratulations! You qualify for a discount." : "Add more items to your cart to qualify for a discount."; return message; ``` # Data Types ## Numbers Represent numeric values, which can be either integers (whole numbers) or decimals (floating point numbers). This data type is essential for performing calculations, storing quantities, and representing values such as prices or points. - **Returning a Number:** ```javascript const number = 10; return number; // It will return 10 ``` ## Text strings Text strings represent sequences of characters, such as names, descriptions, messages, or any other type of textual information. In JavaScript, text strings are delimited by single ( ' ) or double ( " ) quotes. - **Display a message:** ```JavaScript return `Hello world`; ``` - Display a custom welcome message: ```JavaScript return `Hello, ${v.username}! Welcome to our application.`; ``` - **Concatenate (join) multiple text strings:** ```JavaScript const name = "Mary"; const lastname = "Lopez"; return "Full name: " + first name + " " + last name; // Result: "Full name: María López" ``` ## Booleans (true and false) Booleans represent logical values of true or false. They are essential for making decisions in your code and controlling the execution flow of your application. - **Check if an input field is empty:** ```JavaScript return i.name.trim() === ''; // Returns true if the field is empty, false otherwise ``` ## Objects In JavaScript, objects allow you to group related data into a single structure using key-value pairs. - **Creating an object:** You can create an object using curly braces `{}` and separating properties with commas. Each property has a key (name) and a value, separated by a colon `:`. For example: ```javascript const person = { name: 'John', age: 30, city: 'Madrid', }; // Object created with properties ``` - **Accessing properties:** You can access the value of a property of an object using dot notation or bracket notation. For example: ```javascript const personName = person.name; // "John" - Accessing with dot notation const personAge = person['age']; // 30 - Accessing with bracket notation ``` - **Modifying properties:** If you need to change the value of an existing property, you can assign a new value to its key. For example: ```javascript person.age = 31; // Updates the value of the property "age" to 31 ``` - **Adding properties:** You can add new properties to an object by assigning a value to a new key. For example: ```javascript person.profession = 'Developer'; // Adds the property "profession" to the object ``` ## Arrays (Lists) An array in JavaScript is a structured way to hold an ordered collection of items. Each item in the array has a specific position, allowing you to store a variety of data types, including numbers, strings, booleans, objects, and even other arrays. - **Creating an Array:** To create an array, use square brackets `[]` and separate the elements with commas. For example: ```javascript const myShoppingList = ['apples', 'milk', 'eggs', 'bread']; ``` - **Accessing Elements:** You can access a specific element in an array by using its index in square brackets. Remember that indexes start at 0, meaning the first element has an index of 0, the second has an index of 1, and so forth. For example: ```javascript const firstItem = myShoppingList[0]; // "apples" const thirdItem = myShoppingList[2]; // "eggs" ``` - **Modifying Elements:** You can change the value of an existing element in an array by assigning it a new value using its index. For instance: ```javascript myShoppingList[1] = 'yogurt'; // Replace "milk" with "yogurt" ``` ### Iterating over Arrays: Go through your Data Element by Element RenderList allow you to iterate through arrays and display each element individually on your page, without the need to write manual loops. This feature is invaluable when you need to present data dynamically, such as showing a list of products, users, or messages, with minimal setup. The use of Render List automates the iteration process, making it easier to work with arrays by automatically repeating a template for each element of the array. This means that each item in your data source can be displayed consistently without the need for complex code, allowing you to focus on design and presentation. ### Useful methods for arrays JavaScript offers a variety of methods for working with arrays, such as: - push() : Adds an element to the end of the array. - pop() : Removes the last element from the array. - shift() : Removes the first element from the array. - unshift() : Adds an element to the beginning of the array. - slice() : Creates a copy of a portion of the array. - splice() : Add, remove or replace elements in the array. - map() : Creates a new array by applying a function to each element of the original array. - filter() : Creates a new array with the elements that meet a certain condition. - reduce() : Reduces an array to a single value by applying a function to each element. # How to use AI to create code for Wized Artificial Intelligence (AI) can be an invaluable programming partner in Wized, assisting you in generating JavaScript code snippets quickly and efficiently. Even for those who are new to JavaScript or need to implement complex logic. To use AI effectively in Wized, it is crucial to provide the right context so that it understands the user's needs and generates code that is compatible with the platform. Here's how to do it: 1. **Identify the task:** Clearly define what the user wants to accomplish with the code. Is it to validate a form, display a conditional message, or perform a specific calculation? 2. **Ask a precise question:** Use clear and concise language to describe the task at hand. Include relevant details, such as the names of variables, cookies, or API responses that the user needs to utilize. 3. **Provide context to the AI:** Before asking the question, include the following prompt so that the AI understands the Wized environment and generates appropriate code: ## Snippet ```JavaScript You are assisting a Wized user, a low-code platform integrated with Webflow for creating interactive web applications. The user needs guidance writing JavaScript code within the Wized Function Editor to customize website behavior. Keep the following points in mind: - **Data Access:** Wized offers real-time access to data through specific parameters: - `c`: Cookies (e.g., `c.myCookie`) - `v`: Variables (e.g., `v.myVariable`) - `i`: Inputs (e.g., `i.myInputField`) - `f`: Forms (e.g., `f.myForm.name.email`) - `r`: API Responses (e.g., `r.myRequest.data.price`) - `n`: Navigation (e.g., `n.currentPage`) - **Functions:** Functions within the Function Editor must always return a value using the `return` keyword. - **Syntax:** Ensure the code is valid JavaScript and supported by modern web browsers. - **No `console.log`:** Avoid `console.log` statements, as Wized provides a built-in preview for results. - **No direct DOM access:** Do not use `document.getElementById` or similar DOM access methods, as Wized automatically manages element selection. Now, provide the user with Wized-compatible JavaScript code to answer their question. ``` ## Tips for better results with AI - **Be specific and detailed in your questions:** The clearer and more precise your task description is, the better the AI-generated code will be. - **Include examples:** If possible, provide examples of how you would like the end result to look or function. - **Mention relevant actions or settings:** If your code is related to a specific Wized action or setting, please mention this in your question so the AI can generate more contextualized code. # Introduction The Function Editor is a vital tool within Wized that empowers you to add custom logic and enhance the interactivity of your web applications. This guide will outline the importance of the Function Editor and explain how it integrates with events, actions, and element configurations. ::: tip Note Most customizations you need can be achieved using simple and intuitive JS logic. Even if you have no prior coding experience. For more information on how to use GPT to create snippets, check out our [guide here](https://tu-enlace.com). ::: ## Importance of the Function Editor 1. **Custom Logic Implementation**: The Function Editor enables you to write JavaScript code that dictates your application’s behavior based on specific conditions. This feature is essential for creating dynamic interactions and delivering personalized user experiences. 2. **Conditional Logic**: With the Function Editor, you can establish conditions that determine when certain actions or configurations should occur. This capability allows your web application to respond to user inputs or API responses in real-time, eliminating the need for page reloads. 3. **Work with Elements, Events and Actions**: The Function Editor seamlessly integrates with events (such as clicks or form submissions) and actions (tasks executed in response to events). This synergy facilitates the programming of complex workflows and interactions, enhancing the overall functionality of your application. ## How It Works with Events and Actions **Events**: - Events represent user interactions that trigger actions, such as clicking a button or submitting a form. Wized provides the functionality to "listen" for these events and execute corresponding actions. - You can incorporate conditions within the Function Editor to determine whether an action should execute based on the event's context, such as verifying if a user is logged in. **Actions**: - Actions refer to the tasks your application performs in response to events. Common actions include changing element visibility, setting text, or making API requests. - The Function Editor allows you to specify custom conditions for these actions, enabling intricate logic that significantly enhances user experience. For example, you may wish to execute an API request only if specific form fields contain valid data. **Element Configurations**: - In Wized, you can configure UI components (elements) to behave differently based on real-time data or user interactions. The Function Editor is where you define these behaviors using JavaScript. - The configurations you establish will automatically respond to changes in application state, ensuring that the user interface reflects the most current data or user actions without requiring manual updates. ## Examples - **Dynamic Welcome Messages**: Utilize the Function Editor to display a welcome message exclusively for registered users by checking a cookie that indicates their login status: ```javascript return c.isUserLoggedIn ? 'Welcome back!' : ''; ``` - **Form Validation**: Conduct real-time validation of form inputs and show error messages when inputs do not meet specific criteria: ```javascript return i.password.value.length < 8 ? 'Password too short' : ''; ``` - **API Interaction**: Perform an API request only if a user has accurately filled out a form: ```javascript return i.name.trim() !== '' && i.email.trim() !== ''; ``` # Window Overview The **Function Editor** of Wized is organized into two main areas, designed to enhance your coding experience and facilitate result visualization. ![function-editor-window-overview](fe_panel.png) ## 1. Text Area In the **Text Area**, you can write JavaScript functions that execute within Wized. This editor operates similarly to traditional code editors. Within the Wized environment, you have access to [specific parameters](https://your-link.com) that allow you to interact directly with the application's state data. ![text-area](text-area.png) ## 2. Result Area The **Result Area** shows the output of your code after execution. By clicking the **Test Button**, the code in the Text Area executes, and the returned data is presented in various formats, including text, numbers, arrays, and objects. Some specific use cases for each format are: ![result-panel](result-panel.png) :::tip Note You can expand or collapse each property of an object or array, making it easier to analyze data and providing better visual control over the results. ::: ### Buttons Area ![buttons](buttons.png) - **Test**: Executes the code written in the Text Area and updates the Result Area with the output. - **Open Data Store**: Opens a floating window displaying the current contents of the Data Store. - **Prettify**: Improves code readability by automatically formatting it. - **Documentation**: Shortcut to Wized documentation - **Wrap code**: Resizes the code to fit the window, eliminating the need for horizontal scrolling. # Introduction The parameters in Wized allow easy access to various types of data within the Function Editor. Each parameter represents a specific type of information, making it easier to work with real-time data across different areas of the application. ## c: Access to Cookies - ```javascript return c; //Returns an array with all cookies and their values ``` - ```javascript return c.cookie_name: //Returns the specific value of the indicated cookie. For more information, refer to the Cookies section. ``` ## f: Access to Forms - ```javascript return f: // Returns an array of all created forms, where each form is an object that includes inputs as properties. ``` - ```javascript return f.form_name: //Returns an object with the inputs of a form (name, email, password, etc.). ``` - ```javascript return f.form_name.email: //Returns the value of the "email" input within the form ``` :::tip Note - In order for Wized to recognize forms, they must have the Wized attribute. - Form values ​​are only accessible after the form has been submitted; ::: ## i: Access to Input Fields - ```javascript return i : // Returns a list of all recognized inputs on the current page. ``` - ```javascript return i.input_name : // Returns the real-time value of the specified input. ``` :::tip Note In order for Wized to recognize inputs, they must have the Wized attribute, Refer to the [Input Fields section](../data-store/inputs) for more information. ::: ## n: Access to Navigation - ```javascript return n.href : // Returns the current URL value. ``` - ```javascript return n.parameter : // Returns an object with all previously defined URL parameters. ``` - ```javascript return n.parameter.parameter_name : // Returns the specific value of a real-time parameter. ``` - ```javascript return n.path : // Returns the current navigation path. ``` ## r: Access to Requests - ```javascript return r : // Returns a list of all requests and their values. ``` - ```javascript return r.request_name : // Returns the result, headers, and status of an executed request. ``` ## v: Access to Variables - ```javascript return v : // Returns an array of all defined variables along with their values. ``` - ```javascript return v.variable_name : // Returns the specific value of the indicated variable. ``` ## t: Access to the Wized Element Object Provides access to the [Wized Element](../javascript-api/#the-wizedelement-object) object that defines the element that is associated with the function. This parameter is only available for element actions. ## e: Access to the event data (Optional) Provides access to the event data on an element's event eg on click. # Initial Configuration ## First Steps Set up your first project in Wized and start adding advanced functionality and custom logic to your website: 1. **Create your account on Wized:** - Go to [Wized](https://app.wized.com/) and create a free account. 2. **Create your first project:** - Once inside the Wized dashboard, click on the "New Project" button. 3. **Connect your project to Webflow:** - **Staging URL:** Paste the URL of your Webflow development site (webflow.io). - **Project Name:** Choose a unique and descriptive name to identify your project in your workspace. - **Wized Script:** - Copy the script provided by Wized and paste it into the custom code `` section of your Webflow project. - Ensure there are no conflicting scripts already present in the head section. - In Webflow, go to the Website Settings panel. - Look for the "Custom Code" section. - Paste the Wized script into the `` section. - Save changes and publish your site. - **Now, you’re ready! Click the “Create” button to finalize your project.** 4. **View your site in the Wized configurator:** - You will now see an exact replica of your website inside the Wized configurator. This interactive version allows you to experiment and add features in real-time! 5. **Connecting Elements:** - Wized recognizes all elements on your Webflow site. To enable interactivity for specific elements, you must establish a connection between those elements and Wized. - **Add the wized attribute:** - In Webflow, go to the settings of the element you want to connect to Wized. - Find the "Custom Attributes" section and add a new attribute. - The key must be `wized` and the value will be the name you will use to identify this element in Wized (for example, `myButton`, `myForm`, etc.). - **Save your changes and republish your site.** You should now be able to see this element in the Wized Elements panel and start adding functionality to it! # Wized Attribute The Wized attribute is essential for configuring elements on your Webflow website within the Wized platform. By adding this attribute to any element, the Wized configurator can dynamically identify and manage the elements you wish to customize, allowing you to add specific configurations and behaviors. ## How to Configure the Wized Attribute in Webflow 1. **Select the Element**: Identify the HTML element on your website to which you want to apply the Wized Attribute. 2. **Access the Settings Tab**: Navigate to the Settings tab for the selected element. 3. **Custom Attributes Section**: Locate the Custom Attributes section. 4. **Add a New Attribute**: Create a new attribute using the key `wized`. 5. **Define a Unique Value**: Assign a unique value as the element name, such as `button-submit` or `product-card`. This value is crucial within Wized for identifying the specific element and applying the appropriate settings. > **Important**: Ensure that each name is unique. If you assign the same name to multiple elements, they will inherit the same behavior and logic, which can lead to unexpected results. The Wized Attribute is compatible with all native Webflow elements as well as custom HTML elements, providing you with flexible integration options into your design. By utilizing this attribute, you can harness the capabilities of the Wized Configurator to implement custom data and logic, thus delivering an interactive and tailored experience for your application users. # Available Actions for Global Events - **Perform a Request:** Executes a specific request to an API. You can add an optional condition using the Function Editor to control when the request is executed. For example, you can chain multiple requests, executing one only if the previous one was successful. - **Set Cookie:** Updates the value of an existing cookie or creates a new one. You can use the Function Editor to define the new value of the cookie and add optional conditions. - **Set Variable:** Updates the value of an existing variable or creates a new one. You can use the Function Editor to define the new value of the variable and add optional conditions. - **Navigate to:** Redirects the user to another URL or route within your application. You can add an optional condition using the Function Editor to control when the redirection occurs. For example, you can redirect the user to a login page if they are not authenticated. - **Run Function:** Executes a custom JavaScript code snippet. You can use this action to perform complex tasks or programmatically interact with elements on your page. For example: ## Examples and Use Cases ### 1. Perform a Request This action allows you to send a request to an external API in response to a global event. You can use it to fetch updated data, send information to a server, or perform any other operation that requires communicating with an external service. **Example:** - **Event:** Page Load Complete - **Action:** Perform a Request to get user profile data from an API. - **Configuration:** - **Request:** Select the API request you want to execute (e.g., getUserData). - **Condition (optional):** You can add a condition in the Function Editor to control when the request is executed. For example, only if the user is authenticated: ```javascript // Check if there is an authenticated user return c.loggedUser; ``` ### 2. Set Cookie This action allows you to create a new cookie or update the value of an existing one. Cookies are useful for storing information in the user's browser, such as preferences, session data, or authentication tokens. **Example:** - **Event:** Request Completed (associated with a login request) - **Condition:** r.loginRequest.ok (True if the login was successful) - **Action:** Set Cookie to create a cookie named tokenUsuario with the value of the authentication token received from the API: ```javascript // Returns the authentication token from the login return r.loginRequest.data.token; ``` ### 3. Navigate to This action allows you to redirect the user to another page or URL within your application or to an external site. You can use it to create custom navigation flows or send the user to a specific page after completing an action. **Example:** - **Event:** Request Completed (associated with a user registration request) - **Condition:** r.registroUsuario.ok (True if the registration was successful) - **Action:** Navigate to redirect the user to the login page: ```javascript // Returns the URL of the login page return '/login'; ``` ### 4. Run Function This action allows you to execute a custom JavaScript code snippet in response to a global event. It is useful for performing complex tasks, interacting with DOM elements, or implementing logic that cannot be achieved with predefined actions. **Example:** - **Event:** Page Load Start - **Action:** Run Function to initialize an external JavaScript library and configure it: ```javascript // Make sure to have imported the library in your Webflow project return initializeMyLibrary(); ``` # Types of Events in Wized 1. **Custom Condition:** This event enables you to establish a specific condition using the Function Editor. The event will activate when the defined condition evaluates to true. You can leverage various data types available in Wized—such as variables, cookies, API responses, or user input values—to construct intricate, customized conditions. 2. **Attribute Present:** This event is triggered when Wized identifies an element on the currently selected page that possesses a specific Wized attribute. It is particularly useful for executing actions when a designated component loads or when specific criteria within your page structure are satisfied. 3. **Request Finished:** This event occurs immediately after a particular API request concludes, whether successfully or with an error. You can utilize this event to handle the API response, update the user interface, or carry out additional actions based on the result of the request. 4. **Page Starts Loading:** This event takes place when the page begins to load in the user's browser. It is optimal for initializing variables, retrieving data from APIs, or executing other preparatory tasks prior to the page becoming visible to the user. 5. **Page Finishes Loading:** This event is activated when the page has completely loaded in the user's browser. You can use this moment to perform final checks, reveal elements that were hidden during the loading phase, or initiate animations and transitions. ## **When to use Page Starts Loading vs. Page Finishes Loading?** The answer depends on when you need those actions to take place and what impact they will have on the user experience. - **Page Starts Loading:** This event is triggered the moment the page begins to load, even before the user sees anything on their screen. It is ideal for: - **Early actions:** Tasks that need to be performed as soon as possible, such as displaying a loading indicator or **initializing critical variables** that are necessary for the page load. - **Fetch data early:** Making requests to APIs or databases to have the information ready when the user needs to interact with the page. - **Page Finishes Loading:** This event is fired once all elements of the page have loaded and are ready for use. It is perfect for: - **Content-dependent interactions:** If you need to manipulate specific elements on the page, perform animations, or apply logic that requires all content to be present, now is the time to do it. - **Final Checks and Validations:** Performing security checks, validating forms, or verifying the user's authentication status after the page has fully loaded. - **Optimize performance:** If you have tasks that may slow down the initial loading of the page, such as loading images or heavy scripts, execute them at the end of the page load to improve the user experience. # Global Events Global events in Wized are triggers that you can set to run automatically at specific times or when certain conditions are met, without requiring direct user interaction with your website. These events enable you to perform essential tasks and automate background processes, such as loading data at startup, checking permissions, or responding to system events. # When to Use Global Events Consider implementing global events in the following scenarios: 1. **Performing Actions at Page Load:** - If you need to load initial data, display loading indicators, or conduct security checks at the start or end of page loading, global events are ideal. 2. **Responding to System Events:** - Use global events to handle API responses, manage errors, or take action based on the presence of specific elements on the page. 3. **Creating Automated Workflows:** - Set up global events to trigger automated processes, such as sending email notifications after successful registrations or updating external databases in response to changes within your application. # Introduction Wized serves as an intelligent layer on top of your Webflow website, allowing you to add advanced functionality and custom logic without the need to write complex JavaScript code. It facilitates the connection between your Webflow website and the world of web applications. You don't need to be a programming expert to create dynamic and customized web applications. Wized provides a visual, intuitive, and secure environment to design functionalities such as: - Connecting to external APIs - Managing user interface elements - Rendering dynamic content - Adding custom logic ## How does it work? 1. **Design in Webflow:** - Start by creating the structure and visual design of your website in Webflow. 2. **Integration with Wized:** - Add the Wized script to the `` of your Webflow project to establish the connection between your design and the Wized platform. 3. **The Wized Configurator:** - Once connected, Wized creates a real-time replica of your website within its Configurator. This is where the magic happens. 4. **Add interactivity:** - Use the Elements Panel to select the elements in your design that you want to make interactive. Assign events or custom settings to them. 5. **Writing Logic in the Function Editor:** - Control the behavior of your elements and create more complex interactions by writing simple JavaScript code in the Function Editor. 6. **Wized does the rest:** - Wized translates your logic into concrete actions, updates the user interface in real time, and communicates with external services through APIs if necessary. ## Why Choose Wized? - **Simplicity without Sacrificing Power**: Say goodbye to the complexities of traditional coding. Wized offers an intuitive interface, enabling your team to incorporate advanced features into your website without requiring extensive programming skills. For more on getting started, visit our [Setup Guide](./getting-started/). - **Accelerate Development**: Achieve advanced functionality in a fraction of the time it would typically take to code from scratch. This means your team can focus on innovation rather than repetitive tasks. - **Seamless Webflow Integration**: Wized integrates directly with your Webflow projects, allowing your team to leverage existing designs and enhance interactivity without starting from scratch. Explore the [Initial configuration](./getting-started/) to see how it works. - **Flexibility and Customization**: With Wized, your team has full control over application behavior. Create custom interactions, connect to external APIs, manage data, and much more. - **Effortless Collaboration**: Wized facilitates collaboration between designers and developers, enabling seamless integration between visual design and application logic. # JavaScript API Wized offers a JavaScript API to extend your web apps with custom logic, providing access to the following features: - The project configuration. - The Data Store. - The Wized Elements. - Global events. - Request helpers. Most of these functionalities can be accessed right from inside the [Function Editor](../function-editor/index.md), but in some cases you might want to use the JavaScript API directly from your own code. ## Initialize The following wrapper will ensure that the Wized API is loaded before executing your code: ```js window.Wized = window.Wized || []; // [!code focus:2] window.Wized.push((Wized) => { // Your code goes here }); // [!code focus] ``` ## The `Wized` object ### `Wized.version` - **Type:** `string` Returns the current version of the Wized Embed library. This is useful when debugging your app. ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { console.log(Wized.version); }); ``` ### `Wized.config` - **Type:** `WizedConfig` Returns the project configuration that was loaded by Wized. This is useful when debugging your app. ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { console.log(Wized.config); }); ``` ### `Wized.data` - **Type:** `DataStore` Contains your project's Data Store, also known as your app's state. ```typescript type DataStore = { c: Record; f: Record>>; i: Record>; v: Record; r: Record; n: { href: string; path: string; parameter: Record; }; }; type WizedRequestData = { id: string; number: number; data: unknown; // The response data headers: Record; // The response headers isRequesting: boolean; hasRequested: boolean; statusText: string | null; status: number | null; ok: boolean | null; duration: number; }; ``` #### Reading values from the Data Store You can read any value from the Data Store by simply accessing the `Wized.data` object properties: ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { console.log(Wized.data.v.my_variable); console.log(Wized.data.c.my_cookie); }); ``` #### Updating values in the Data Store You can update any value in the Data Store by simply assigning a new value to the `Wized.data` object properties or mutating them: ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { // Normal assignments Wized.data.v.my_variable = 'New value'; Wized.data.n.parameter.id = 1234; // Array updates Wized.data.v.items.push('New item'); Wized.data.v.items.sort(); Wized.data.v.items = [...Wized.data.v.items, 'Newer item']; // Nested objects Wized.data.f.my_form = { name: 'John', email: 'john@doe.com', }; }); ``` Updates to: - Variables (`v.my_variable`): will trigger any reactivity associated to them. This applies to any other field in the Data Store too. - Cookies (`c.my_cookie`): will set the new cookie value to the browser. To remove cookies, just set the value to `null`. - Parameters (`n.parameter.my_parameter`): will set the new parameter value to the current URL. To remove parameters, just set the value to `null`. - Inputs (`i.my_input`): will set the new input value to the input field. Each field expects the correct value type: - Text inputs: `string` - Number and range inputs: `number` - Checkboxes: `boolean` - Checkbox groups: `Array` - Radio groups: `string` - Select dropdowns: `string` - Multi-select dropdowns: `Array` - Forms (`f.my_form`): any field of a form can be updated using the field name. The expected value types are the same as Inputs (`i`). - Update a single field: `Wized.data.f.my_form.name = "John"` - Update multiple fields: `Wized.data.f.my_form = { name: 'John', email: 'john@doe.com' };` - Requests (`r.my_request`): although it’s possible to update requests state using the API, it’s not recommended as it can create conflicts with the native Actions & Requests. ### `Wized.reactivity.watch()` Watches one or more reactive Data Store values and invokes a callback function when the sources change. Example: ```typescript window.Wized = window.Wized || []; window.Wized.push((Wized) => { Wized.reactivity.watch( () => Wized.data.v.my_variable, (newValue, oldValue) => { console.log(`my_variable changed from ${oldValue} to ${newValue}`); } ); }); ``` Example with multiple values: ```typescript window.Wized = window.Wized || []; window.Wized.push((Wized) => { Wized.reactivity.watch( [() => Wized.data.v.my_variable, () => Wized.data.v.my_other_variable], ([newVar, newOtherVar], [oldVar, oldOtherVar]) => { console.log(`my_variable changed from ${oldVar} to ${newVar}`); console.log(`my_other_variable changed from ${oldOtherVar} to ${newOtherVar}`); } ); }); ``` This function is provided by Vue's [@vue/reactivity](https://www.npmjs.com/package/@vue/reactivity) package, [the full documentation can be found here](https://vuejs.org/api/reactivity-core.html#watch). ### `Wized.reactivity.effect()` Runs a function immediately while reactively tracking any Data Store values and re-runs it whenever those values are changed. Example: ```typescript window.Wized = window.Wized || []; window.Wized.push((Wized) => { Wized.reactivity.effect(() => { console.log(Wized.data.v.my_variable); }); }); ``` This function is provided by Vue's [@vue/reactivity](https://www.npmjs.com/package/@vue/reactivity) package, [the full documentation can be found here](https://vuejs.org/api/reactivity-core.html#watcheffect). ### `Wized.requests.execute()` - **Type:** `(identifier: string) => Promise` The function expects an identifier of the request that can be either the Request ID or the Request name. Triggers a request and returns a Promise with the [WizedRequestData](#wizeddata). Example: ```typescript window.Wized = window.Wized || []; window.Wized.push(async (Wized) => { const result = await Wized.requests.execute('request_name'); console.log(result); }); ``` ### `Wized.requests.waitFor()` - **Type:** `(identifier: string) => Promise` The function expects an identifier of the request that can be either the Request ID or the Request name. Returns a Promise that resolves when the request has finished. As opposite to [Wized.requests.execute](#wizedrequestsexecute), this method does not execute the request, only awaits for it to finish. ```js window.Wized = window.Wized || []; window.Wized.push(async (Wized) => { const result = await Wized.requests.waitFor('request_name'); // This will not trigger a request execution console.log(result); }); ``` ### `Wized.requests.getClient()` - **Type:** `(identifier: string) => Promise` ::: warning Warning This is an advanced feature and should only be used if you know what you are doing. ::: The function expects an identifier that can be either a Request ID, a Request name, an App ID or an App name. Returns the client used to execute the request. This is useful when you need to interact with the SDK client directly via custom code. Currently only [Supabase](https://supabase.com/docs/reference/javascript/introduction) and [Firebase](https://firebase.google.com/docs/reference/js) clients are supported, and the returned object will be one of the following: ```typescript type WizedClientData = | { type: 'supabase'; version: string; // The version of the SDK, i.e. "2.39.7" client: SupabaseClient; // https://supabase.com/docs/reference/javascript/initializing } | { type: 'firebase'; version: string; // The version of the SDK, i.e. "10.8.1" app: FirebaseApp; // https://firebase.google.com/docs/reference/js/app.firebaseapp.md#firebaseapp_interface} auth: Auth; // https://firebase.google.com/docs/reference/js/auth.auth.md#auth_interface firestore: Firestore; // https://firebase.google.com/docs/reference/js/firestore_.firestore.md#firestore_class storage: FirebaseStorage; // https://firebase.google.com/docs/reference/js/storage.firebasestorage.md#firebasestorage_interface }; ``` You can use this method to interact with the client like this: ```js window.Wized = window.Wized || []; window.Wized.push(async (Wized) => { const { version, client } = await Wized.requests.getClient('my_supabase_app'); // You should check the client version before using it, as the API might change between versions if (version.startsWith('2')) { const user = await client.auth.getUser(); } }); ``` Notice how in the example above we check the client version before using it. This is an important step because Wized may update the client version in the future, and the API might change between versions. ::: warning Important Wized reserves the right to update client versions without prior notice, it's the developer's responsibility to keep their code prepared for newer versions of the SDKs. ::: In case you need additional methods from the original npm package, you can use the provided version to dynamically import it: ```js window.Wized = window.Wized || []; window.Wized.push(async (Wized) => { const { version, auth } = await Wized.requests.getClient('my_firebase_app'); // Dynamically import the Firebase package const firebaseAuth = await import(`https://cdn.jsdelivr.net/npm/firebase@${version}/auth/+esm`); if (version.startsWith('10')) { firebaseAuth.signOut(auth); } }); ``` ### `Wized.elements.get()` - **Type:** `(name: string) => WizedElement` Returns a [WizedElement](#the-wizedelement-object) instance by its name. If there are multiple elements with the same name, it will just return the first one. ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { const element = Wized.elements.get('element_name'); }); ``` ### `Wized.elements.getAll()` - **Type:** `(name?: string) => WizedElement[]` Returns an array of all the app's [WizedElement](#the-wizedelement-object) instances. If a name is provided, it will return all the elements with that name. ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { const elements = Wized.elements.getAll(); // Returns all the elements const elementsWithName = Wized.elements.getAll('element_name'); // Returns all the elements with the name "element_name" }); ``` ### `Wized.on()` - **Type:** `(eventName: string, listener: (event: Event) => void) => void` Listens for global events of the app. The following events are available: #### `Wized.on('requeststart', listener)` This event is fired when a request is triggered. The listener callback receives an object with the request name and ID. ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { Wized.on('requeststart', (result) => { console.log(`Request ${result.name} was triggered`); }); }); ``` #### `Wized.on('requestend', listener)` This event is fired when a request execution finalizes. The listener callback receives a [WizedRequestData](#wizeddata) object. ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { Wized.on('requestend', (result) => { console.log(`Request ${result.name} finalized executing after ${result.duration}ms`); }); }); ``` ## The `WizedElement` object For each element that is defined with a `wized = "element_name"` HTML attribute in Webflow, Wized creates a `WizedElement` instance that is used for several purposes: - Store element-specific state. - Store the element's actions and cleanups. - Store the element's node or anchor (when not rendered). - Store the element's clones when applying a [Render List](../elements/configuration-types/single-use/render-list) action. - Store the element's child tree. ### `WizedElement.name` - **Type:** `string` Returns the element name. ### `WizedElement.rendered` - **Type:** `boolean` Returns `true` if the element is currently rendered on the page, `false` otherwise. The rendered state is controlled via the [Set Visibility](../elements/configuration-types/single-use/set-visibility) action. ### `WizedElement.node` - **Type:** [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) Returns the element's DOM node. This is useful when you need to interact with it directly instead of using Wized's actions. The node is only present in the DOM when the element is [rendered](#wizedelementrendered). ### `WizedElement.anchor` - **Type:** [Comment](https://developer.mozilla.org/en-US/docs/Web/API/Comment) The element's anchor is a placeholder comment that is put in place when the element is not rendered. This is useful when you need to interact with it directly instead of using Wized's actions. The anchor is only present in the DOM when the element is not [rendered](#wizedelementrendered). ### `WizedElement.parent` - **Type:** `WizedElement | undefined` Returns the element's parent [WizedElement](#the-wizedelement-object) instance, if any. ### `WizedElement.children` - **Type:** `WizedElement[]` Returns an array of the element's child [WizedElement](#the-wizedelement-object) instances. ### `WizedElement.clones` - **Type:** `WizedElement[]` Returns an array of the element's clones. Clones are created when applying a [Render List](../elements/configuration-types/single-use/render-list) action. ### `WizedElement.data` - **Type:** `Record` A reactive object used to store element-specific data. This object is shared across all the element's tree (parents and children). ### `WizedElement.on()` - **Type:** `(eventName: string, listener: (event: Event) => void) => void` Adds a lifecycle event listener to the element. The listener will be removed when the element is destroyed. ```js window.Wized = window.Wized || []; window.Wized.push((Wized) => { const element = Wized.elements.get('element_name'); element.on('attribute', (event) => { console.log(`Attribute ${event.key} was updated to ${event.value}`); }); }); ``` The following events are available: #### `WizedElement.on("attribute", listener)` This event is fired when the element's attributes are updated via a [Set HTML Attribute](../elements/configuration-types/multi-use/set-html-attribute.md) action. The listener callback receives the following event object: - `event.key`: The HTML Attribute key. - `event.value`: The new value. #### `WizedElement.on('class', listener)` This event is fired when the element's CSS classes are updated via a [Set Class](../elements/configuration-types/multi-use/set-class) action. The listener callback receives the following event object: - `event.className`: The CSS class name. - `event.valid`: Defines if the class was added or removed. #### `WizedElement.on('list', listener)` This event is fired when the element's clones are updated via a [Render List](../elements/configuration-types/single-use/render-list) action. The listener callback receives the following event object: - `event.addedClones`: The added element clones. - `event.updatedClones`: The clones that were kept in the DOM. - `event.removedClones`: The clones that were destroyed. #### `WizedElement.on('parameter', listener)` This event is fired when the element's URL parameters are updated via a [Set URL Parameter](../elements/configuration-types/single-use/add-parameter-to-link.md) action. The listener callback receives the following event object: - `event.name`: The URL parameter name. - `event.value`: The new value. #### `WizedElement.on('style', listener)` This event is fired when the element's inline styles are updated via a [Set Style](../elements/configuration-types/multi-use/set-style.md) action. The listener callback receives the following event object: - `event.style`: The style name. - `event.value`: The new value. #### `WizedElement.on('text', listener)` This event is fired when the element's text is updated via a [Set Text](../elements/configuration-types/single-use/set-text.md) action. The listener callback receives the following event object: - `event.type`: The type of update that was made (text, html or markdown). - `event.value`: The new value. #### `WizedElement.on('value', listener)` This event is fired when the element's input value is updated via a [Set Input Value](../elements/configuration-types/single-use/set-input-value) action. The listener callback receives the following event object: - `event.value`: The new value. #### `WizedElement.on('visibility', listener)` This event is fired when the element's render state is updated via a [Set Visibility](../elements/configuration-types/single-use/set-visibility) action. The listener callback receives the following event object: - `event.displayed`: Defines if the element was added or removed from the DOM. > [!NOTE] > To use this method, you will need to enable authentication in the App configuration # Airtable Requests ## What is an Airtable Request? An Airtable request is a way to integrate your Application with Airtable. You can retrieve data, create new records, update existing ones, or delete information with Airtable as your backend database. You can use Airtable to just fetch data without any authentication like in public blogs, or you can use authentication build by Wized so users can create account, sign in, read and write data based on permission setup in Wized configurator. To create airtable requests you will need to first create an Airtable Wized App. ## How to Create Airtable App ### 1. Go to My Apps Begin by going to the 'My Apps' panel in Wized. 1. Click the `+` button at the top of the panel. 2. Add a name for your app for later reference, i.e. `Airtable App`. 3. Pick the `Airtable` option. ![Adding an Airtable App to my apps](my-apps.png) 4. Connect Airtable using OAuth and select bases you want to use with this app 5. Click "Add base" and select Airtable Base 6. Click "Grant access" and wait for the authorization ![Connect Airtable Oauth Popup](wized-airtable-connect-popup.png) ### 2. Configure your request #### Create a new request, and add basic info - Name your request i.e. `get_blog_posts` - Add your request to a folder (optional) - Select your Airtable App from the dropdown ![Adding basic info to our request](airtable-request.png) #### Select method You will need to select one of the methods for a specific functionality - [Create user](./methods/authentication/create-user/index.md) Create a user with specified email and password and store in the table you selected in app configuration - [Login user](./methods/authentication/login-user/index.md): Login a user with email and password - [Load user](./methods/authentication/load-user/index.md): Load authenticated user - [Logout user](./methods/authentication/logout-user/index.md): Sign out currently authenticated user - [Delete user](./methods/authentication/delete-user/index.md): Delete currently authenticated user - [Request password reset](./methods/authentication/request-password-reset/index.md): Request password reset - [Password reset](./methods/authentication/password-reset/index.md) Reset password with new password - [Get item](./methods/data/get-item/index.md): Get Airtable Record item - [Get list items](./methods/data/get-list-items/index.md): Get Airtable Record list of items - [Create item](./methods/data/create-item/index.md): Create Airtable Record - [Update item](./methods/data/update-item/index.md) Update Airtable Record - [Delete item](./methods/data/delete-item/index.md): Delete Airtable Record ### 3. User authentication If you want to have an authentication system on your app, you just need to check "Enable authentication" in the app configuration ![Enable authentication](enable-user-authentication.png) Select Base from which you want to store and retrieve users Select table from which you want to store and retrieve users In the selected table you will need to have two fields, email and password Select email and password fields and you are ready to go. Go to the Requests panel and start configuring your request. ## Create user method With "Create User" method, you can implement sign-up functionality in your application. Users will be saved in the Base and table you selected in the [App configuration](../../../index#how-to-create-airtable-app). - All passwords will be encrypted! ### Parameters - Email: This is a required [function field](../../../../../function-editor/index.md) where you can return the user's email. - Password: This is a required function field where you can input the user's password. - Page: This is an optional function field where you can input the URL of the page to which you want to redirect the user after successful sign-up. - Auto Login: This is a checkbox field that lets Wized know if you want to automatically sign in the new user or not. ![User Create Method](user-create-method.png) ## Delete user method With "Delete User" method, you can implement delete user functionality in your application. User will be deleted from the Base and table you selected in the App configuration. ![User delete Method](delete-user.png) ## Load user method With "Load User" method, you can fetch current authenticated user! This usually need to be done when app loads the first time, then you can save that on app state! Users will be retrieved from the Base and table you selected in the App configuration. ### Parameters - Page: Page url to redirect after loading the user. ![User Load Method](load-user-method.png) ## Login user method With "Login User" method, you can implement sign-in functionality in your application. Users will be retrieved from the Base and table you selected in the App configuration. ### Parameters - Email: This is a required [function field](/function-editor/) where you can input the user's email. - Password: This is a required function field where you can input the user's password. - Page: This is an optional function field where you can return the URL of the page to which you want to redirect the user after successful login. ![User Login Method](login-user-method.png) ## Login with magic link method With "Login with magic link" method, you can implement passwordless sign in functionality in your application. You will first need to use ["Send magic link"](../send-magic-link/index) method to send the link to the email. This method will get access token from the link that is build from "Send magic link" method and will login user! ### Parameters - Redirect url: This is an optional [function field](../../../../../function-editor/index.md) where you can redirect user after successful sign in! ![Login with magic link method](login-with-magic-link.png) ## Logout user method With "Logout User" method, you can implement logout functionality in your application. This will clear the current user data from the application state and you can redirect user with page param to the page you want! ### Parameters - Page: Page to redirect after logout! ![User Logout Method](logout-user-method.png) ## Password reset method With "Password reset" method, you can implement password reset functionality in your application. After user click on the link from email that is sent from "Request password reset" method, user will need to be redirected in this page and query params will be added to the page. This need to be called after user will write the new password in the input fields in the page. ### Parameters - New Password: This is a required [function field](/function-editor/) where you can return user's submitted new password. ![Password reset method](password-reset-method.png) ## Request password reset method With "Request password reset" method, you can implement password reset functionality in your application. An email with reset link will be sent to the user email that is returned from email param function. ### Parameters - Email: This is a required [function field](/function-editor/) where you can return user's email. - Redirect url: This is a required function field where you can return the page url in which user will input the new password. ![Request password reset method](request-password-reset-method.png) ## Send email verification link method With "Send email verification link" method, you can implement email verification in your application. This method will send a verify link to the user email and after user go to that link, you will need to call "Verify email" method to verify the email. ### Parameters - Email: This is a required [function field](/function-editor/) where you can return user's submitted email. - Redirect url: This is a required [function field](/function-editor/) where you can return the url of the page in which you plan to redirect user from email. ![Send email verification link method](send-email-verification-link.png) ## Send magic link method With "Send magic link" method, you can implement passwordless sign in functionality in your application. This method will send a login link to the user email and after user go to that link, you will need to use the "Login with magic link" method to login user to your application. ### Parameters - Email: This is a required [function field](/function-editor/) where you can return user's submitted email. - Redirect url: This is a required [function field](/function-editor/) where you can return the url of the page in which you plan to redirect user from email. ![Send magic link method](send-magic-link-method.png) ## Verify email method With "Verify email" method, you can implement last step of email verification functionality in your application. This method will get access token from the link that is build from "Send email verification link" method and will verify the email! ### Parameters - Redirect url: This is an optional [function field](/function-editor/) where you can redirect user after successful email verification! ![Verify email method](verify-email-method.png) ## Create item method With "Create item" method, you can create a record from the specified Base and Table. ### Main Parameters - Base: This is a required dropdown field where you can select the base you want to create the record into. - Table: This is a required dropdown field where you can select the table you want to get the record into. ![Create item method](create-item-method.png) ### Permissions You can select who can create record You can select from: - Allow Any: Any user can create a record - Authenticated: Any authenticated user can create record - Owner: Authenticated user can create the record, and user id will be stored into record. If you select this option, you will need to select also the field in which you will store user id ![Owner permissions](../../../owner-permissions.png) ### Fields Airtable fields will be listed as function fields, in which you will need to specify for each one what value will be returned. ## Delete item method With "Delete item" method, you can delete an existing record from the specified Base and Table. ### Main Parameters - Base: This is a required dropdown field where you can select the base you want to delete existing record from. - Table: This is a required dropdown field where you can select the table you want to delete existing record from. - Record ID: This is an required function field where you can return the record id that you want to delete. ![Delete item method](delete-item-method.png) ### Permissions You can select who can delete record You can select from: - Allow Any: Any user can delete the record - Authenticated: Any authenticated user can delete the record - Owner: Authenticated user can delete the record if the user id field value will match with authenticated user. If you select this option, you will need to select also the field in which you will store user id > [!NOTE] > In most cases you need to select Owner here, so only users that created the record can also delete it. ![Owner permissions](../../../owner-permissions.png) ## Get item method With "Get item" method, you can retrieve a single airtable record from the specified Base and Table. ### Main Parameters - Base: This is a required dropdown field where you can select the base you want to get the record from. - Table: This is a required dropdown field where you can select the table you want to get the record from. - Record ID: This is an required function field where you can return the record id that you want to retrieve. - Limit fields to: This is an optional multi select dropdown field in which you can select fields that you want to retrieve. ![Get item method](get-item-method.png) ### Permissions You can select who can retrieve this record You can select from - Allow Any: Any user can retrieve this record - Authenticated: Any authenticated user can retrieve this record - Owner: Only the user that created this record can retrieve it - If you select Owner, you will need to select also the field in which the user id is stored ![Owner permissions](../../../owner-permissions.png) ## Get list items method With "Get list items" method, you can retrieve and filter multiple records from the specified Base and Table. ### Main Parameters - Base: This is a required dropdown field where you can select the base you want to get items from - Table: This is a required dropdown field where you can select the table you want to get items from - Limit fields to: This is an optional multi select dropdown field in which you can select fields that you want to retrieve. - View: This is an optional required dropdown field where you can select the view you want to get items from ![Get list items method](get-list-items.png) ### Permissions You can select who can retrieve the data You can select from: - Allow Any: Any user can retrieve the data - Authenticated: Any authenticated user can retrieve the data - Owner: Only records that user field value will match with currently authenticated user id will be retrieved - If you select Owner, you will need to select also the field in the user id is stored > [!NOTE] > In most cases you need to select Owner here, so only users that created the records can also retrieve them. ![Owner permissions](../../../owner-permissions.png) ### Filter Parameters You can add multiple filters and each filter will need to have params: - Include record if: This is a required dropdown field in which you will need to select table field to apply filter to - Condition: This is a required dropdown filed with values Equals, Does not equal, Includes, Does not include - Value: This is a required function field, in which you will need to select the value to test with condition ![Filtering](get-list-items-filtering.png) ### Filtering Records Based on Reference Fields To filter records based on a reference table field, you need to create a lookup field for that table and select the field you want to filter with. _Figure 1: Example of a reference field_ ![Reference Field](get-list-reference-fields-filtering.png) _Figure 2: Configuration of a reference field for filtering_ ![Reference Field Configuration](get-list-reference-fields-filtering-config.png) ### Pagination Parameters You can paginate airtable records result with following params: - Page size: The number of records returned in each request. Must be less than or equal to 100. Default is 100. - Offset: To fetch the next page of records, include offset from the previous request in the next request parameters. - Max records: The maximum total number of records that will be returned in your requests. If this value is larger than pageSize (which is 100 by default), you may have to load multiple pages to reach this total. ![Pagination](get-list-pagination.png) ### Sort Parameters You can add multiple sort conditions and each condition will need to have params: - Sort by: This is a required dropdown field in which you will need to select table field to apply sorting - Order: This is a required dropdown filed with values Ascending, Descending ![Sorting](get-list-sorting.png) ## Update item method With "Update item" method, you can update an existing record from the specified Base and Table. ### Main Parameters - Base: This is a required dropdown field where you can select the base you want to update existing record. - Table: This is a required dropdown field where you can select the table you want to update existing record. - Record ID: This is an required function field where you can return the record id that you want to update. ![Create item method](update-item-method.png) ### Permissions You can select who can update record You can select from: - Allow Any: Any user can update a record - Authenticated: Any authenticated user can update record - Owner: Authenticated user can update the record if the user id field value will match with authenticated user If you select this option, you will need to select also the field in which you will store user id > [!NOTE] > In most cases you need to select Owner here, so only users that created the record can also update it. ![Owner permissions](../../../owner-permissions.png) ### Fields Airtable fields will be listed as function fields, in which you will need to specify for each one what value will be returned. # Creating Native Requests Wized simplifies integration with popular services through pre-configured native requests, including support for Firebase, Memberstack, Airtable, and Supabase. These native requests are designed so that users do not need to perform complex manual configurations or consult the full documentation for each service, as Wized provides the necessary options directly in a drop-down menu. When choosing a service from the drop-down menu, Wized will display the specific request types you can create based on the selected service. :::tip Note Please refer to the section for each native integration for more information. ::: # Confirm Password Reset The `Confirm password reset` method is used to set a new password for a user existing in your Firebase app. It requires an `OOB Code` that is obtained by first [sending a password reset email to the user](../send-password-reset/index.md). To make a request to confirm a password reset, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Confirm password reset`. 3. Provide the new `Password` and the `OOB Code` received from the [Send password reset email](../send-password-reset/index.md), usually through the page query parameters. ![Confirm password reset Firebase](confirm_password_reset_1.png) # Create Item The `Create Item` method enables you to add a document to a collection in your Firebase Cloud Firestore. To create a request to add a document to a collection, follow the steps below: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Create Item`. ![Create Item Firebase](create_item_1.png) 3. Under the `Path`, fill in the full path to the collection in your Cloud Firestore database. ![Create Item Firebase](create_item_2.png) 4. Add the data of the new document to be added in key-value pairs. ![Create Item Firebase](create_item_3.png) # Delete Item The `Delete Item` method allows you to delete a specific document or an entire collection from your Cloud Firestore. To create a request to delete a document or collection, follow the steps below: 1. Open the request panel and click on the `+` button to add a new request. 2. Provide an appropriate name for the request and select the Firebase app to be used for the request. Then, choose `Delete Item` as the method. 3. In the `Path` field, enter the full path to the document or collection in your Cloud Firestore database. ![Delete Item Firebase](delete_item_1.png) # Get File URL The `Get File URL` method is used to obtain the full public-facing URL paths to your file in Cloud Storage in Firebase. To make a request to get the file URL, follow these steps: 1. First, ensure you have Cloud Storage set up on your Firebase app. :::info NOTE The clip starts with the project in test mode - this isn't secure. You'll need to update the Firebase rules. ::: 2. Open the request panel and click on the `+` button to add a new request. 3. Fill in an appropriate name for the request and select the Supabase app to be used for the request. Then, under the method, choose `Get File URL`. 4. Scroll down to fill in the bucket name and storage path of the file. You can then choose whether to download it or just display it. ![Get File URL Firebase](get_file_url_1.png) # Get Item The `Get Item` method allows you to fetch a specific document from your Cloud Firestore. To create a request to get an item, follow the steps below: 1. Open the request panel and click on the `+` button to add a new request. 2. Provide an appropriate name for the request and select the Firebase app to be used for the request. Then, choose `Get Item` as the method. 3. Fill in the full path to the document in your Cloud Firestore database under the `Path` field. ![Get Item Firebase](get_item_1.png) ::: info NOTE In most cases, the Get Item request requires the document ID at the end of the path. ::: # Get items list The `Get items list` method allows you to fetch a collection from your Cloud Firestore. To create a request to get a collection, follow the steps below: 1. Open the request panel and click on the `+` button to add a new request. 2. Provide an appropriate name for the request and select the Firebase app to be used for the request. Then, choose `Get items list` as the method. ![Get Item list Firebase](get_list_1.png) 3. Fill in the full path to the collection in your Cloud Firestore database under the `Path` field. ![Get Item list Firebase](get_list_2.png) The `Limit items` field is optional, but for much larger collections, we do advise using it. The `Subscribe realtime` checkbox allows you to listen to your data and receive real-time updates. 4. (Optional) If you want to filter, you can provide a field path to filter by, as well as the criteria to filter by. In the screenshot below, we are filtering by the `name` field path, and we only want those matching the value `John Doe` to be returned. ![Get Item list Firebase](get_list_3.png) 5. (Optional) If you want to sort, you can provide a field path to sort by, as well as the direction to sort by. In the screenshot below, we are sorting by the `name` field path in ascending order. ![Get Item list Firebase](get_list_4.png) 6. (Optional) To paginate your results, you can use one of the following methods: a. Start After Use this method to begin pagination after a specific value. ![Get Item list start after Firebase](get_list_pagination_start_after.png) b. Start At Use this method to begin pagination at a specific value. ![Get Item list start after Firebase](get_list_pagination_start_at.png) c. Multiple Fields Pagination To paginate with multiple fields, specify sort by for the fields you want, and define the starting point as a list. ![Get Item list multiple fields](get_list_pagination_multiple.png) # Get User The `Get User` method is used to retrieve the details of the currently logged-in user using Firebase. To make a request to get a user, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Get user`. ![Get User Firebase](get_user_1.png) # Firebase Requests Wized has a native Firebase integration, which makes it easy to make requests to your Firebase app to perform CRUD operations on Cloud Firestore. Firebase is a popular Backend-as-a-Service (BaaS) that provides a real-time database. It is a NoSQL database that stores data in JSON-like documents. ## How to get started? ### Creating a project in the Firebase console To start using Firebase, first, you need to create a project in [the Firebase console](https://console.firebase.google.com/). You'll see a screen similar to the one below. ![Firebase console](./introduction_2.png) Click on the `Add Project` button and follow the on-screen prompts. Not much customization is needed for this sample app, so just clicking on continue for all steps with the default settings will be okay. ### Adding an app to your project in the Firebase console After successfully creating a project, you'll be presented with this screen where we should add our app. ![Firebase console successful project creation](./introduction_5.png) Since what we are building is a web app, we will click on the `` button, which will give us a set of credentials to use in Wized. You'll then give it an appropriate name, and on the step of adding the Firebase SDK, we will choose to do so via script tags. Copy the `firebaseConfig` values for use in setting up the Firebase app in Wized. ![Firebase console config](./introduction_4.png) ### Setting up Firebase in the Wized configurator In the Wized configurator, go to `My Apps`, then click on the `+` button to add an app. Give the app an appropriate name, and under the `App` option, choose `Firebase`. Next, transfer the data from the Firebase config copied earlier onto Wized. The final result will be as below: ![Firebase console](./introduction_3.png) ### Creating Cloud Firestore After creating an app, we'll need to add a database to store our data, and that is where Cloud Firestore comes into play. Check out an example below of creating the Cloud Firestore and manually adding a document to it. ### Securing your database Firebase implements security rules to protect your data. It is very important that you take the time to understand how to write these rules to ensure your data is secure. Otherwise, anyone can potentially read or write to your database. Check out the [Firebase documentation](https://firebase.google.com/docs/firestore/security/get-started) for more information. # Send Password Reset The `Send password reset` method is used to send an email to an existing user in Firebase for password resetting. To make a request to send a password reset email, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Send password reset`. 3. Under the Email menu, fill in the email (or use an [input field](../../../data-store/inputs.md) or [form field](../../../data-store/forms.md)). ![Send password reset Firebase](send_password_reset_1.png) # Set Item The `Set Item` method works similarly to the [Create Item](../create-item/index.md) method but performs upserting instead. If the document already exists, the `Set Item` method will overwrite the existing document with the new data provided or merge the new data with the existing data in the document, depending on whether the `Merge Fields` option is active. If the document does not exist, the `Set Item` method will create a new document with the provided data. ## Example Request 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Set Item`. ![Set Item Firebase](set_item_1.png) 3. Under the `Path`, fill in the full path to the document in your Cloud Firestore database. ![Set Item Firebase](set_item_4.png) 4. Fill in the key-value pairs with the data to be set. ![Set Item Firebase](set_item_3.png) # Sign in with email and password The `Sign in with password` method is used to authenticate an existing user to your application using the traditional format of providing an email and a password. To make a request to sign in a user using an email and password, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Supabase app to be used for the request. Then, under the method, choose `Sign in (email + password)`. ![Sign in Firebase](sign_in_1.png) 3. Scroll downwards under the Email menu, fill in the email (or use an [input field](../../../data-store/inputs.md) or [form field](../../../data-store/forms.md)), and then fill in the password. ![Sign in Firebase](sign_in_2.png) # Sign in with OAuth provider The `Sign in with provider` method is used to authenticate a user to your site using a widely used third-party application providing OAuth. To make a request to authenticate a user using OAuth, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Supabase app to be used for the request. Then, under the method, choose `Sign in with OAuth`. ![Sign in with OAuth Firebase](sign_in_1.png) 3. Scroll downwards to select the provider and add a redirect URL. ![Sign in with OAuth Firebase](sign_in_2.png) 4. Add the scopes required for your app. ![Sign in with OAuth Firebase](sign_in_3.png) :::info NOTE **Scopes** vary widely based on the provider used, and each provider has a sample of scopes on their respective documentation. An example is Facebook's scopes listed here: [https://developers.facebook.com/docs/permissions](https://developers.facebook.com/docs/permissions) ::: # Sign Out The `Sign Out` method is used to log out an authenticated user using Firebase. To make a request to sign out a user, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Sign Out`. 3. Under the Email menu, fill in the email (or use an [input field](../../../data-store/inputs.md) or [form field](../../../data-store/forms.md)). ![Sign Out Firebase](sign_out_1.png) # Sign up with email and password The `Sign up(email + password)` method is used to add a new user to your application using the traditional format of providing an email and a password. To make a request to sign up a user using an email and password, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Supabase app to be used for the request. Then, under the method, choose `Sign up(email + password)`. ![Sign up Firebase](sign_up_1.png) 3. Scroll downwards under the Email menu, fill in the email (or use an [input field](../../../data-store/inputs.md) or [form field](../../../data-store/forms.md)), then fill in the password. ![Sign up Firebase](sign_up_2.png) # Unsubscribe Real-Time The `Unsubscribe realtime` method lets you stop listening for live changes on your documents from earlier subscribed requests. To create a request to unsubscribe from realtime updates, follow the steps below: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Unsubscribe realtime`. 3. Under the `Requests`, choose the request(s) to stop the realtime events from. ![Unsubscribe realtime Firebase](unsubscribe_realtime_1.png) # Update Email The `Update email` method is used to change the email of a user existing in Firebase. To make a request to update a user's email, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Update email`. 3. Under the Email menu, fill in the email (or use an [input field](../../../data-store/inputs.md) or [form field](../../../data-store/forms.md)). ![Update email Firebase](update_email_1.png) # Update Item The `Update item` method enables you to change the details of a document in your Firebase Cloud Firestore. To create a request to update a document, follow the steps below: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Update item`. ![Update item Firebase](update_item_1.png) 3. Under the `Path`, fill in the full path to the document in your Cloud Firestore database. ![Update item Firebase](update_item_2.png) :::info NOTE: Almost all of the time, the update item request needs the document ID at the tail end of the path. ::: 4. Fill in the key-value pairs with the data to be changed. ![Update item Firebase](update_item_3.png) # Update Profile The `Update profile` method is used to change the user's profile information in Firebase like the display name and photo URL. To make a request to update a user's profile, follow these steps: 1. Open the request panel and click on the `+` button to add a new request. 2. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Update profile`. 3. Add the new `Display Name` or `Photo URL` for the user. # Upload File The `Upload file` method is used to upload files to your Firebase cloud storage. 1. First, ensure you have cloud storage added to your Firebase app. ::: info NOTE The clip starts with the project in test mode - this isn't secure. You'll need to update the Firebase rules. ::: 2. Open the request panel and click on the `+` button to add a new request. 3. Fill in an appropriate name for the request and select the Firebase app to be used for the request. Then, under the method, choose `Upload file`. 4. Scroll down to fill in the storage path of the file. Use an [input field](../../../data-store/inputs.md) or [form field](../../../data-store/forms.md) to choose the file to be uploaded. ![Upload file Firebase](upload_file_2.png) # Handling API Errors ## When the request cannot be sent It means that it did not reach the destination API server. This can happen for several reasons: - **Incorrect configuration in Wized:** Carefully review your request configuration in the Requests panel. Make sure the endpoint URL, HTTP method (GET, POST, etc.), headers, and body are correct and match the API requirements. - **API service is temporarily down:** Sometimes the API server may be experiencing technical issues or undergoing maintenance. In this case, the request will not be able to reach its destination. - **The API does not accept direct requests from the browser:** Some APIs are configured to accept requests only from servers, not directly from the user's browser. Wized, by default, sends requests from the browser, which can cause problems in these cases. Use secrets to send your REST requests through our servers to avoid this problem. ### How to investigate if the request is not sent? - **Check the Logs Dashboard and Data Store:** If the request is not sent, you will usually see a 500 error code and a description like "failed to fetch" in the "States" tab of the request in the Data Store Dashboard. This indicates that the request did not reach the API server. - **Check your request configuration:** Carefully review the endpoint URL, HTTP method, headers, and body in the Requests Dashboard. Make sure they match the API documentation. - **Check the API service status:** If you suspect the problem is with the API server, visit the provider's website or search online for information about the service status. - **Consider using Secrets or Native Integrations:** If the API doesn't accept direct requests from the browser, you can use the "Secrets" feature in Wized to send the request through our servers. You can also check if Wized offers a native integration with the service you're using, as these integrations usually handle communication with the API more securely and efficiently. ## If the request returns an error If the request reaches the API server but the API encounters a problem, it will respond with an HTTP error code. These codes are standardized messages that indicate the type of problem encountered. Some of the most common ones are: - **400 Bad Request:** The request is poorly formatted or missing required data. - **401 Unauthorized:** You need to provide valid authentication credentials. - **403 Forbidden:** You do not have permission to access the requested resource. - **404 Not Found:** The resource you are looking for does not exist. - **500 Internal Server Error:** There is a problem with the API server. ### How to investigate - **Check the HTTP status code:** In the "Statuses" tab of the request in the Data Store Panel, you will find the HTTP status code of the response. Look up its meaning online to understand the type of error. - **Examine the response body:** Many APIs provide detailed error messages within the response body (in the "Body" tab of the Data Store Panel). These messages will give you more specific information about the problem. - **Check the API documentation:** The API documentation will help you interpret the error codes and specific messages you receive, and offer solutions or steps to take to resolve the issue. ## Troubleshooting Tools Your best ally for troubleshooting API issues in Wized is the **Data Store Panel** . Here you can: - **View the request status:** Check whether the request was executed successfully ( hasRequested and isRequesting ), whether there was an error ( ok ), and the HTTP status code ( status ). - **Inspect the response:** Examine the headers and body of the response for details about the error or information returned by the API. - **Compare with documentation:** Consult the API documentation to understand the structure of the expected response and possible error codes. ## Difference between HTTP error codes and errors in the Body - **HTTP Status Codes:** These are numeric responses sent by the API server that indicate the overall outcome of the request (success, error, redirect, etc.). You can find a list of HTTP status codes here - **Errors in the Body:** Some APIs, even when returning a 200 (OK) status code, may include detailed error messages within the response body (in the "Body" tab of the Data Store Panel). These messages will give you more specific information about the problem. # Requests ## Introduction API requests serve as the essential communication link between your web application and various services available on the internet. These requests enable you to perform a range of actions—such as retrieving weather data, processing online payments, or sending automated emails—by facilitating secure and efficient data exchange with these services. Allowing you to accomplish these tasks without the need for complex coding. # Memberstack Requests The [Memberstack](https://www.memberstack.com/) integration enables granular control over user access to your application, as well as managing user data and subscriptions. ## How to use Memberstack in Wized Memberstack can be used as a standalone App in Wized or in conjunction with Memberstack's `