What causes let to lose significance within the context of React development?

In my React code snippet, I am encountering an issue with the organizationId variable. Even though I can see its value in the first and second instances, I am unable to see it in the third instance. This strange behavior is occurring in a Next.js based project.

function Event(props: EventProps) {
  const { lang, translations, eventId } = props;
  const [event, setEvent] = useState<EventOut | undefined>();
  const [enableSaleSwitch, setEnableSaleSwitch] = useState<boolean>(false);
  const [
    enableSaleSwitchOnWordpress,
    setEnableSaleSwitchOnWordpress,
  ] = useState<boolean>(false);
  let isTiketAdmin: string | null;
  let jwt: string | null;
  let eventIdNew: string | undefined;
  let organizationId: string | undefined;
  let organization: OrganizationOut | undefined;
  let userFbId: string | null;
  let permission: string | undefined;

  useEffect(() => {
    isTiketAdmin = localStorage.getItem("isTiketAdmin");
    jwt = localStorage.getItem("jwt");
    userFbId = localStorage.getItem("userFbId");
  }, []);

  useEffect(() => {
    organizationId = getOrganizationFbIdFromEventId(eventId);
    if (organizationId != undefined) {
      organization = getOrganizationByFbId(organizationId!);
      if (organization && userFbId) {
        permission = organization.usersWithPermission[userFbId];
        setEvent(organization.events[eventId]);
      }
    }
  }, [eventId]);

  useEffect(() => {
    if (event) {
      if (checkEnableSaleOnTiket(event, eventId)) {
        setEnableSaleSwitch(true);
      } else {
        setEnableSaleSwitch(false);
      }
      if (checkEnableSaleOnWordPress(event, eventId)) {
        setEnableSaleSwitchOnWordpress(true);
      } else {
        setEnableSaleSwitchOnWordpress(false);
      }
    }
  }, [event]);

https://i.sstatic.net/r7Q3A.gif

Answer №1

It is important to explain the events and reasons why they do not meet expectations, rather than just sharing a GIF image.

In terms of providing an actual answer, consider the significance of including organizationId in the dependency array for that useEffect.

The sequence of events is as follows:

  1. During the first render, all useEffects are set to execute.
  2. The second hook runs first (disregarding the unrelated first hook), assigning a value to organizationId.
  3. This second hook then calls setEvent, triggering a re-render at a later point.
  4. Subsequently, the third hook runs (in "parallel") and recognizes the updated value.
  5. A second render occurs, initiated by step 3.
  6. The second hook does not run because there was no change in eventId. Its dependency array specifies that the hook effect should only be rerun when eventId changes, hence organizationId remains unchanged.
  7. The third hook is executed due to the alteration in event. Since the previous hook did not run during this render (as observed in step 6), the variable is left unset.

If there is a variable that needs to persist between renders and interact with hooks, it should be managed as a state variable or a ref using either useState or useRef, based on whether updating the variable triggers a component re-render.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

javascript include new attribute adjustment

I am working with this JavaScript code snippet: <script> $('.tile').on('click', function () { $(".tile").addClass("flipOutX"); setTimeout(function(){ $(".tile-group.main").css({ marginLeft:"-40px", widt ...

Is there a way to create a self-contained installation package for my Vue application?

Is it possible for my application to be downloaded and installed without requiring internet access after the download is complete? I am looking to create a standalone installer for this purpose. Are there any suggestions on how to go about implementing t ...

Switch the custom audio control button on and off within a v-for loop

I have implemented a unique audio play/pause button in my Vue app for a list of audios. Here is how it looks: <div v-for="(post, p) in post_list"> ... ... ... <v-avatar v-if="!is_played" color="#663399" ...

Utilizing Audio Record Feature with a pair of buttons - one for initiating recording and the other for concluding recording

I'm new to Vue.js and trying to create a simple audio recorder that starts recording on click of a button and stops when another button is clicked. The goal is to display the audio file in the template and save it locally as a blob. Here is the templ ...

Setting configuration files in Node.js with npm configuration

I have developed a SAAS application on the Angular/NodeJS/Postgres+MongoDB stack that can establish connections with customer databases, cloud warehouses, S3 buckets, and more to load relevant information. Once I receive connection details from the Angular ...

Creating dynamic canvas elements with images using HTML and JavaScript

Currently, I am working on a unique project involving a canvas filled with dynamic moving balls. This project is an extension or inspired by the codepen project located at: https://codepen.io/zetyler/pen/LergVR. The basic concept of this project remains t ...

The class name is not defined for a certain child element in the icon creation function

Currently, I am developing a Vue2 web application using Leaflet and marker-cluster. I am encountering an issue with the iconCreateFunction option in my template: <v-marker-cluster :options="{ iconCreateFunction: iconCreateClsPrg}"> ...

Imitating the Frameset Separator's Actions

The latest HTML5 specification has eliminated the <frameset> element. One useful feature of the <frameset> tag that is hard to replicate without it is: In a frameset, you can adjust the position of the frame divider line with the mouse. Is t ...

The Jenkins build report shows success, however, the website is currently inaccessible

Here are the shell commands I use in Jenkins to build a Next.js Hello World app and deploy it on my local machine in a different directory. You can view the Jenkins shell command and check out the console output. To configure the ecosystem file, click her ...

Utilizing the push method to add a JavaScript object to an array may not be effective in specific scenarios

When I tried using users.push within the 'db.each' function in the code below, it didn't work. However, moving the 'users.push' outside of it seemed to do the trick. Is there a way to successfully push the new objects from db.each ...

What is the process of invoking a JavaScript function from Selenium?

How can I trigger a JavaScript function from Selenium WebDriver when using Firefox? Whenever I am logged into my website, I typically utilize this command in Firebug's Command Editor to launch a file upload application: infoPanel.applicationManager. ...

Is there a way for me to gain access to the ng-repeat scope?

I have a scenario where my ng-repeat generates different elements and I need to perform certain operations, such as creating variables, within the scope of the ng-repeat. Is there a way to access the specific ng-repeat scope? How can I achieve something ...

The usage of ngRoute clashes with the functionality of Animated Scroll

I am experiencing a conflict between my ng-route and the animated scroll feature on my website: Below is the code for my scroll element: <a href="#one" class="goto-next scrolly">Next</a> In this code, "#one" represents the section ID to scro ...

How to pass an item as a parameter to a computed property in Vue.js, and have it return a sorted child array within a

After spending some time searching on Google, I am still struggling to find a solution for this issue. I have a list of "Intents" that contain nested lists of "Entities" created using v-for loops. The Intents are already computed, but now I need to dynam ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Learn how to implement a split background effect by simply clicking the SPLIT button

let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.width = window_width; canvas.height = window_height; let hit_counter = 0; // object is created using class clas ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

What is causing the issue with this API request's functionality?

I have set up an API using Django-REST Framework and am currently working on connecting it to my frontend. One of the endpoints I created retrieves the last four winners, and when I test it, everything seems to be functioning properly. async function getL ...

Using JQuery to Execute Matching Based on Text Within <A> Elements

After reviewing the resources on Jquery Extract URL from Text and jquery match() variable interpolation - complex regexes, I am still a bit confused. The issue at hand is that I have a webpage with a dropdown menu at the top. Inside the dropdown, there ...

Only the first element can trigger reactions in jQuery and Ajax!

I am facing an issue on this particular page where I have several forms that can be optionally submitted using ajax. The problem lies in the fact that only the first element selected by jQuery is getting executed! Below is the JavaScript code: $(function ...