I want to add progress bar to switch from one screen to another

I am working on a react app. It has simple auth features. The problem is that after a user sign’s up, they are forced to wait 6-9 seconds before the landing page loads.

For that reason, I want to add a progress bar as a popup after the user clicks on the SIGN-UP button to notify the user that the page is loading.

 const handlePress = () => {
if (!firstName) {
  Alert.alert("First Name is required");
} else if (!phone) {
  Alert.alert("Phone Number is required.");
} else if (!email) {
  Alert.alert("Email Field is required.");
} else if (!password) {
  Alert.alert("Password Field is required.");
} else {
  registration(email, password, phone, firstName);
  navigation.navigate("Welcome");
  emptyState();
}
  };

<TouchableOpacity style={styles.button} onPress={handlePress}>
      <Text style={{ fontWeight: "bold", color: "#fff", fontSize: 18 }}>
        {" "}
        Sign Up
      </Text>
    </TouchableOpacity>

Someone Help. Relatively new to react and JS.

Using JavaScript Fetch() and formData() To Update A Database

I have some javascript fetch() on a project and, although it works, the issue I have is, (although I understand the basics of fetch and formData), the piece of code seems overly complicated for what it is doing, and I don’t understand how it is working?

I have some PHP that when a download button is clicked it updates a ‘downloads’ count in a MySQL database. I’ve included the PHP at the end, but it isn’t really relevant to the issue.

What I don’t understand is if the form button is assigned to a downloadButton variable, why the code is written how it is, particularly on the click event listener?

It would be amazing if someone could explain this to me and possibly show a better way of doing it using the downloadButton variable?

I’ve added code comments on the parts I don’t understand.

Also please feel free to explain this as if you are talking to an idiot – I am new to JavaScript/software development.

JavaScript

let forms = document.querySelectorAll('.download-form-js'),
    downloadButton = document.querySelectorAll('.dl-button')

// URL details
let myURL = new URL(window.location.href), // get URL
pagePath = myURL.pathname // add pathname to get full URL

if (forms) {
        forms.forEach(item => {
            
            // Why is it done like this when a variable is assigned to the download button above?
            item.querySelectorAll('[type="submit"], button').forEach( button => {
                button.addEventListener("click", e => item._button = button); //store this button in the form element?
            })

            // The 'btn' parameter in this function isn't used ?
            item.addEventListener("submit", function(evt, btn) {

                evt.preventDefault();

                const formData = new FormData(this);

                // Can the parameters inside the '.set()' function not be done with the 'downloadButton' variable?
                if (this._button) // submitted by a button?
                {
                    formData.set(this._button.name, this._button.value);
                    delete this._button; // have no idea why this is even used?
                }

            fetch (pagePath, {
                method: 'post',
                body: formData
            }).then(function(response){
                return response.text();
            // }).then(function(data){
            //     console.log(data);
            }).catch(function (error){
                console.error(error);
            })

        })

    })

} // end of if (forms)

PHP (not really relevant, but thought I’d include it)

Below is the PHP function that is used to update the downloads count but isn’t really relevant to the above problem.

function downloadCounter($connection, $imageID) {
    if (isset($_POST['download'])) {
         // value from hidden form element
         $imageID = $_POST['image-id'];

         try {
              $sql = "UPDATE lj_imageposts SET downloads = downloads +1 WHERE image_id = :image_id";
              $stmt = $connection->prepare($sql);

              $stmt->execute([
                   ':image_id' => $imageID
              ]);

         } catch (PDOException $e) {
              echo "Error: " . $e->getMessage();
         }
    }
}

how to use $.ajax in server controller

I have an array of URLS is one of my api functions and I want to check if they exist or not.After some research I realized that i need to use $.ajax with HEAD type to see if an URL exists or not.

Only problem I have never used ajax and jQuery on a node project before and when I npm installed jquery and required it, it didn’t work
this is what i did so far

var $ = require( "jquery" );

module.exports={
 addallreport:function(req,res){
 //code to get the list
    for (let i in list)
    {
        const jsonURL="http://mydomain"+list[i]+"/report.json"
        $.ajax({
            type: 'HEAD',
            url: jsonURL,
        success: function() {
                console.log("page exist")
        },
        error: function() {
                console.log("page does not exist")
        }
        }); 
    }
  }
    }

Use effect wait for Data from previous page

I’m kinda new to the react framework.
As per my requirement , I want to wait until data arrives and binds to my constants in my useEffect() method.

The data is sent encrypted from the main page and is decrypted as follows :

useEffect(() => {
    const DecryptedGroupID = atob(groupID.toString());
    const DecryptedFactoryID = atob(factoryID.toString());

    setProfitAndLossDetails({
      ...ProfitAndLossDetails,
      groupID: DecryptedGroupID,
      factoryID: DecryptedFactoryID
    });
  }, []);

I want to add a waiter/timer/delay to wait until the data gets bound to my const variables. (atob is a decrypting function).

The groupID is required to generate the factoryIDs for the specific group, hence during page reload since it takes time / delay for the hooks to bind, the factoryIDs won’t load at times(however when refreshing it appears sometimes), I think adding a delay and giving it time to bind might fix this issue.

Iframe in react component keeps reloading

My goal is to have a page where I show multiple iframes and I switch between them using a TabList component from mui.
What I want is to load each iframe only once to then be able to switch between tabs without having the iframe reloading again.
Here is what I currently do:

function DashViewer(props: any) {
  let { slug } = useParams();

  const [dashboardEntity, setDashboardEntity] = useState<any | null>(null);
  const [displayedEmbedRank, setDisplayedEmbedRank] = useState("0");
  const { currentUser } = useAuth();

  useEffect(() => {
    const initialize = () => {
      currentUser.getIdToken(true).then(function (idToken: any) {
        fetch("/dashboards/viewer/", {
          method: "post",
          headers: {
            Authorization: idToken,
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ slug: slug }),
        })
          .then((response) => response.json())
          .then((responseData) => {
            setDashboardEntity(responseData.data.dash_infos);

          });
      });
    };
    return initialize();
  }, []);

  const handleChange = (event: React.SyntheticEvent, newValue: string) => {
    setDisplayedEmbedRank(newValue);
  };

  return (
    <Stack spacing={0}>

      <TabContext value={displayedEmbedRank}>
        <Box
          sx={{ borderBottom: 0 }}
          alignItems="center"
          justifyContent="center"
        >
          <TabList onChange={handleChange} centered>
            {dashboardEntity != null &&
              dashboardEntity.embeds.authorizations.map(
                (embed: any, rank: any) => (
                  <Tab label={embed.label} value={rank} />
                )
              )}
          </TabList>
        </Box>
      </TabContext>

      {dashboardEntity != null &&
        dashboardEntity.embeds.authorizations.map(
          (embed: any, rank: any) =>
           (rank == displayedEmbedRank  && (
                <Embed name={dashboardEntity.meta.name} i={rank} hide={false}/>
           )
            )
        )}

      {dashboardEntity != null &&
        dashboardEntity.embeds.authorizations.map(
          (embed: any, rank: any) =>
            rank != displayedEmbedRank  && (
                <Embed name={dashboardEntity.meta.name} i={rank} hide={true}/>
            )
        )}

    </Stack>
  );
}

The DashViewer components is where I generate my tabs and show a different Embed (see below) component based on a state controlled by the tabs. I pass a ‘hide=true’ prop on the Embed component
I want to show and false on the others.

function Embed(props: any) {

  return (
    <div {...(props.hide == true && { style: { display: "none" } })}>
        <Iframe name={props.name} i={props.i}/>
    </div>
  );
}

Embed is basically a wrapper around an Iframe component I made, I use the hide prop to hide the div if necessary.

function Iframe(props:any) {
    return (
        <iframe
        name={`embed-${props.i}`}
        frameBorder="0"
        scrolling="no"
        src={`/dashboards/viewer/${props.name}/${props.i}`}
        style={{
          display: "block",
          background: "#1F3B50",
          height: "calc(100vh - 60px)",
          width: "calc(100vw - 0px)",
          margin: "auto",
          border: "none",
        }}
      ></iframe>
    )
}

Iframe is very simple it just contains an iframe component.

Currently it switches iframes when I click the different tabs but it always reloads the whole iframe each time.
What I understand is that as displayedEmbedRank is part of the state, each Embed component is re-rendered each time the displayedEmbedRank state changes.
What I tried so far is trying React.memo() on Iframe as I thought it wouldn’t re-render again if it already did for a set of given props, but it didn’t seem to work either.

Rails – Ajax: ActionController::UnknownFormat

I am trying to build an ecommerce site using RoR. I have this logic where the user can add more or less quantity to the product they would like to purchase:

<%= link_to order_item_path(item, 'minus'), remote: true, method: :patch do %>
  <button>-</button>
<%end %>
<%= item.quantity %>
<%= link_to order_item_path(item, 'plus'), remote: true, method: :patch do %>
 <button>+</button>
<%end %>

So every time they click on plus or minus, a patch call is sent to the OrderItems controller:

def update
 #do some logic
 respond_to do |format|
   format.js 
   format.html { redirect_to new_charge_path }
 end
end

In the controller we do some logic and I don´t want the page to refresh but to use JavaScript to make the number go up or down. I want to do that using js.erb:

#order_items/update.js.erb

console.log("plus minus") 
#here make number go up or down

The problem is that when the user clicks the button of plus or minus, I get an error:

ActionController::UnknownFormat in OrderItemsController#update
respond_to do |format|
 format.js 
 format.html { redirect_to new_charge_path }
end

Anyone knows why it is happening and how could I solve it? Thanks!

Logout button doesn’t respond when clicked in React.js

I’ve made a simple logout button/function that I’m almost certain that should work but it doesn’t and there isn’t any error either. Here’s my code:

import {Link} from 'react-router-dom';
import { CredentialsContext } from '../App';
import Todos from '../Components/Todos';

export default function Welcome() {
  const [credentials, setCredentials] = useContext(CredentialsContext)
  const logout = () => {
    setCredentials(null);
  }
  return (
    <div>
        {credentials && <button onChange={logout}>Logout</button>}
        <h1>Welcome {credentials && credentials.username}</h1>
        {!credentials &&<Link to="/register">Register</Link>}
        <br/>
        {!credentials &&<Link to="/login">Login</Link>}
        {credentials && <Todos/>}
    </div>
  )
}```

Any chance my backend might have something to do with it?

Hi all. Can anyone decipher might be wrong with this script? [closed]

the code above is supposed to submit 2 forms using one submit button and populate the values in respective Marketo fileds. However, it’s intermittent and doesn’t always work… It runs off the back of the Marketo forms2 API. Does anything particular stand out to you about it?

Thanks!

var lpFields = {"lpId":14586,"subId":117,"munchkinId":"217-ZRF-245","lpurl":"//pages.fitbit.com/HP-Referral-Submit.html?cr={creative}&kw={keyword}","followupLpId":14560};
  var pageFields = MktoForms2.getPageFields();
  form.addHiddenFields(lpFields);
  form.addHiddenFields(pageFields);
  if(window.mktoPreFillFields){
    form.setValuesCoerced(mktoPreFillFields);
  }
  if(!form.EnableDeferredMode){
    form.render();
  }
});     

})();

https://jsfiddle.net/b4xm6nw1/

How to parse such data?(parse json array)

help me pls . I write several arrays to a txt file, and then I want to parse them, what am I doing wrong

fs.readFile("./data.txt", "utf8", 
function(error,dataRes){
  console.log('Читаю данные')
  if(error) throw error; 
  data = JSON.parse('['+dataRes+']'.replace(/][/g,'],['));
  console.log(data)
  createitem();
});

data.txt(example)

[{"update":"Сегодня, 14:44"},{"update":"Сегодня, 14:43"},{"update":"Сегодня, 14:31"}][{},{},{},{"link":"https://www.doska.by//msg/animals/cats/maine-coon/bdnkh.html"}]

checking on url status before fulfilling a promise

I have an atypical use case for the cypress test runner, where I need to start the server from within the cypress.
I’m doing that by defining the before:spechook in cypress plugins/index.jslike so:

module.exports = (on, config) => {
    on('before:spec', async(spec) => {
        // the promise will be awaited before the runner continues with the spec
        return new Promise((resolve, reject) => {
            startServer();
            // keep checking that the url accessible, when it is: resolve(null)
 
            while (true) {
                getStatus(function(statusCode) {
                    if (statusCode === 200)
                        break
                })
            };
            resolve(null)

I’m struggling to implement this while loop that is supposed to keep checking if the url is accessible before fulfilling the before:spec promise.
I have the following function for checking the url:

function getStatus (callback) {
  const options = {
    hostname: 'localhost',
    port: 8080,
    path: '/',
    method: 'GET'
  }
  const req = http.request(options, res => {
  console.log(`statusCode: ${res.statusCode}`)
  callback(res.statusCode}
  })
  req.on('error', error => {
    console.error("ERROR",error)
  })
  req.end()

};

Any help implementing that loop or other suggestions how to achieve the task of checking the url before fulfilling the before:specpromise appreciated.

How to send web push notification for all active users

here I have used the button to send web push notifications. using this button only on the same browser notification came. but I want to send the same push notification to all active users. below is my code.

let applicationServerPublicKey = ‘myKey’;

            var pushButton = document.querySelector('.js-push-btn');
            var pushNotiButton = document.querySelector('.push-btn');

            let isSubscribed = false;
            let swRegistration = null;

            function urlB64ToUint8Array(base64String) {
                const padding = '='.repeat((4 - base64String.length % 4) % 4);
                const base64 = (base64String + padding)
                    .replace(/-/g, '+')
                    .replace(/_/g, '/');

                const rawData = window.atob(base64);
                const outputArray = new Uint8Array(rawData.length);

                for (let i = 0; i < rawData.length; ++i) {
                    outputArray[i] = rawData.charCodeAt(i);
                }
                return outputArray;
            }


            function updateBtn() {
                if (isSubscribed) {
                    pushButton.textContent = 'Disable Push Messaging';
                } else {
                    pushButton.textContent = 'Enable Push Messaging';
                }

                pushButton.disabled = false;
            }

            function updateSubscriptionOnServer(subscription) {
                // TODO: Send subscription to application server
                console.log('subscription'+JSON.stringify(subscription))
                const subscriptionJson = document.querySelector('.js-subscription-json');
                const subscriptionDetails =
                    document.querySelector('.js-subscription-details');

                if (subscription) {
                    //subscriptionJson.textContent = JSON.stringify(subscription);
                    //subscriptionDetails.classList.remove('is-invisible');
                } else {
                    //subscriptionDetails.classList.add('is-invisible');
                }
            }

            function subscribeUser() {
                const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
                swRegistration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: applicationServerKey
                })
                    .then(function(subscription) {
                        console.log('User is subscribed');

                        updateSubscriptionOnServer(subscription);

                        isSubscribed = true;

                        updateBtn();
                    })
                    .catch(function(err) {
                        console.log('Failed to subscribe the user: ', err);
                        updateBtn();
                    });
            }

            function initializeUI() {
                //pushButton.addEventListener('click', function() {
                pushButton.disabled = true;
                if (isSubscribed) {
                    // TODO: Unsubscribe user
                } else {
                    subscribeUser();
                }
                //});

                // Set the initial subscription value
                swRegistration.pushManager.getSubscription()
                    .then(function(subscription) {
                        isSubscribed = !(subscription === null);

                        updateSubscriptionOnServer(subscription);

                        if (isSubscribed) {
                            console.log('User IS subscribed.');
                        } else {
                            console.log('User is NOT subscribed.');
                        }

                        updateBtn();
                    });
            }

            if ('serviceWorker' in navigator && 'PushManager' in window) {
                window.addEventListener('load', function() {
                    navigator.serviceWorker.register('{% url 'sw.js' %}').then(function(registration) {
                        // Registration was successful
                        console.log('ServiceWorker registration successful with scope: ', registration.scope);
                        swRegistration = registration;
                        initializeUI();
                    }, function(err) {
                        // registration failed :(
                        console.log('ServiceWorker registration failed: ', err);
                    });
                });
            }else {
                console.warn('Push messaging is not supported');
                pushButton.textContent = 'Push Not Supported';
            }

            $(".push-btn").click(function(event) {
                console.log('[Service Worker] Push Received.');
                //console.log('[Service Worker] Push had this data: ');
                const title = 'Push Codelab';
                const options = {
                    body: 'Yay it works.',
                    //icon: 'images/icon.png',
                    //badge: 'images/badge.png'
                };
                navigator.serviceWorker.getRegistration().then(reg => {
                    reg.showNotification(title, options);
                });
                //event.waitUntil(ServiceWorkerRegistration.registration.showNotification(title, options));
            });


            let deferredPrompt;
            let addBtn = document.querySelector('#add-home-screen-btn');
            let homeScreenBlock = document.querySelector("#home-screen-btn-block")
            homeScreenBlock.style.display = 'none';
            window.addEventListener('beforeinstallprompt',(e)=>{
                e.preventDefault();
                deferredPrompt = e;
                homeScreenBlock.style.display = 'block';

                addBtn.addEventListener('click',(e)=>{
                    homeScreenBlock.style.display='none';
                    deferredPrompt.prompt();
                    deferredPrompt.userChoice
                        .then((choiceResult)=>{
                            if(choiceResult.outcome === 'accepted'){
                                console.log('Accepted A2SH')
                            }else {
                                console.log('user declined')
                            }
                            deferredPrompt = null;
                        })
                })
            });

This changes when called by different functions? Javascript closure

I’m only started to understand closures when suddenly it throws me another curveball, making my understanding of the scoping in closures even worse. I have a relatively simple closure just so I can get jQuery working inside of an object, which is then called by event handlers outside.

var cwn = (function($) {
    var app = {
        overlay: {
            e: "#sidebar-overlay",
            activate() {
                $(this.e).fadeIn();
                $('body').css('overflow', 'hidden');
            },
            deactivate() {
                $(this.e).fadeOut();
                $('body').css('overflow', 'unset');
            },
        },
        sidebar: {
            e: '#sidebar',
            open() {
                app.overlay.activate();                
                $(this.e).animate({"width": 'show'});
            },
            close() {                
                app.overlay.deactivate();                
                $(this.e).animate({"width": 'hide'}, 'fast');
            }
        }
    };    
    return app;
})(jQuery);

So using it in the console itself or calling the function without the event handlers, results in it working – the sidebar activates and opens up and does what it’s supposed to.

cwn.sidebar.open(); // THIS WORKS JUST FINE

However using this said function with an event handler results in this changing.

$('.hamburger-link').on('click', cwn.sidebar.open); // THIS CHANGES 'this' TO SOMETHING ELSE

Which then causes it to fail.

I have an interim solution – which is to replace this.e with app.sidebar.e but that just seems extremely cumbersome and it just seems to me that there is a better and simpler solution out there.

Type ‘RefObject’ is not assignable to type ‘RefObject’

I am getting this error:

Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement> | undefined; ... 282 more ...; css?: InterpolationWithTheme<...>; } | { ...; } | { ...; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
  Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement> | undefined; ... 282 more ...; css?: InterpolationWithTheme<...>; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
    Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement> | undefined; ... 282 more ...; css?: InterpolationWithTheme<...>; }' is not assignable to type 'ClassAttributes<HTMLInputElement>'.
      Types of property 'ref' are incompatible.
        Type '((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
          Type 'RefObject<HTMLDivElement>' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'.
            Type 'RefObject<HTMLDivElement>' is not assignable to type 'RefObject<HTMLInputElement>'.
              Type 'HTMLDivElement' is missing the following properties from type 'HTMLInputElement': accept, alt, autocomplete, capture, and 51 more.ts(2322)

In this code:

import _ from 'lodash'
import { TextFieldProps } from '@mui/material/TextField/TextField'
...
_renderSimple (sharedProps: TextFieldProps): JSX.Element {
  const inputProps = _.omit(sharedProps, ['className', 'hintText', 'InputProps'])
  return (
    <div className={sharedProps.className}>
      <input
        {...inputProps}
        placeholder={sharedProps.placeholder}
        autoComplete={this.props.autoComplete}
        data-testid={this.props.dataTestId}
      />
      {this._renderError()}
    </div>
  )
}

which in my opinion makes no sense, since I’m putting the inputProps in input, not in div. What am I missing?