How to add Paypal pay later message on AMP

How to add paypal pay later message on AMP pages ?

I am using this –
on head

<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>

on file

<amp-script layout="container" script="hello-world" class="sample">
<div id="pp-pay-later-message"></div>
</amp-script>
<script id="hello-world" type="text/plain" target="amp-script">
console.log("helo---from amp script");
const messageElement = document.getElementById('pp-pay-later-message');
const price = 500;
paypal
  .Messages({
    amount: price,
    style: {
      layout: "text",
      logo: {
        type: "primary",
      },
    },
  })
  .render(messageElement);
paypal.Messages.render(messageElement)
</script>

But nothing display

Anyone have idea how to show a message ?

Why props.children are not rendered on the first render? I have to refresh the page, so then props.children appear on the page

I’m working on the web-app that has a role choice when you visit for the first time. After I choose the admin role for example, it sets the value of userRole in localStorage.

Here is App you can see that depending on the current role there are different routes.

After I have the role chosen, I’m redirected to the ‘/’ route and I actually want to see the component that renders this route which is TableBoard in this case, but instead I firstly get render={() => <Container>its from app.tsx {route.component}</Container>}. So on the first render I only see its from app.tsx, then I refresh the page and everything is fine.

How to fix routing here?

Please ask if something is unclear.

function App() {
  const currentRole = useReduxSelector(state => state.auth.currentRole);
  const accessToken = localStorage.getItem('accessToken');
  const role = localStorage.getItem('role');

  const getCurrentRoutes = () => {
    if (role === 'userCollaborator') {
      return AccRoutes;
    } else if (role === 'userAdmin') {
      return AdminRoutes;
    } else if (role === 'userHr') {
      return HRRoutes;
    } else if (role === 'userPartner') {
      return Routes;
    } else {
      return RoutesAuth;
    }
  };
  const routes = getCurrentRoutes();
  let routesComponents;
  if (currentRole && accessToken) {
    routesComponents = routes?.map(route => {
      return (
        <Route
          key={route.name}
          exact
          path={route.path}
          render={() => <Container>its from app.tsx {route.component}</Container>}
        />
      );
    });
  } else {
    routesComponents = routes?.map(route => {
      return (
        <Route
          key={route.name}
          exact
          path={route.path}
          component={route.component}
        />
      );
    });
  }
  return (
    <BrowserRouter>
      <Provider store={store}>{routesComponents}</Provider>
    </BrowserRouter>
  );
}

export default App;

Component that should be rendered for the route I’m redirected:

export const TableBoard = () => {
  return (
    <Container>
      <div>here I have a lot of other content so it should be rendered as props.children in Container</div>
    </Container>
  );
};

And the code for Components.tsx looks this way:

const Container: React.FC<ContainerProps> = ({children}) => {
  return (
    <div>
      {children}
    </div>
  );
};

export default Container;

How to detect when user tap on the safari topbar to scroll to top?

I’m making an app with Ionic Framework v6 and each page has its own ion-content which handles the scrolling.

Problem is that when the user taps the status bar on iPhoneX (and possibly other iPhones) the apps all handle some sort of ScrollToTop, but ionic has that ion-content to handle the scrolling and therefore the tap on the status bar gets ignored.

Is there anyway to intercept that event? So that I can do the scrollToTop in my code?

Need the values that the user inputs to be added to the same array as predefined values

I need the values that the user inputs in the boxes to be added to the [people] array, so that they can be typed out on the page with the predefined values object1 and object2, together with if they are of legal age or not. I am unsure if I should be using another method for this, the assignment I received was vary vague.

Im new to coding so please forgive any errors.

JS

let nameElement = document.getElementById("UNameInput");
let faultElement = document.getElementById("errorOutput");
let ageElement = document.getElementById("AgeInput");
let clickElement = document.getElementById("button");
let passwordElement = document.getElementById("PasswordInput");
let corrElement = document.getElementById("output");



clickElement.addEventListener("click", function (e) {

    let feedback = [];
    let people = [];


   let object1 = {
       UNameInput: "Marcus",
       ageElement: 33,
   }

   let object2 = {
       UNameInput: "Cihan",
       ageElement: 35,
   }

   people.push(object1, object2)

   console.log(people)


/*
    people.push(new person1("Marcus", 33));
    people.push(new person2("Cihan", 35));
    */

    if (UNameInput.value === '' || UNameInput.value === null) {
       alert('Name input missing')
    }

    else if (AgeInput.value === '' || AgeInput.value === null) {
        alert('Age input missing')
    }
    else if (PasswordInput.value !== 'IHM') {
        alert('Password is not valid')

    } else if (AgeInput.value !== ''){
        if (ageElement.value < 18) {
                feedback.push ( 
                    `Hi your name is ${UNameInput.value}. You are ${AgeInput.value} years old, which is not of legal age. Have a nice day!`
                );
                e.preventDefault()
            
            }
        else {
                feedback.push(
                    `Hi your name is ${UNameInput.value}. You are ${AgeInput.value} years old, which makes you of legal age in Sweden. Have a nice day!`
                );
                e.preventDefault()
            }
    }

    if (feedback.length > 0) {
        e.preventDefault()
        corrElement.innerText = feedback.join(", ")
    }

    else if (people.length > 0) {
        corrElement.innerText = people.join (", ")
    }
});

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inlämningsuppgift</title>


   <!-- Länk till JS-sourcet, det är denna koden som körs--> 
    <script src="JSny copy 2.js" ></script>
</head>

<body>
    <!-- Div för error meddelanden, ifall det skulle vara så att de sker-->
    <div id="errorOutput"></div>  
    
    <!-- P-tag för output av meddelanden, ID-attribut så att vi kan nå den specifikt ifrån JS-->
    <p id="output"></p>

    <!-- Nedanstående del består av 3 divvar, alla har input fält med varsitt ID så att de nås från JS-->
        <div>

            <label for="UNameInput">Name Input</label>
            <input id="UNameInput" name="name" type="text">
        </div>
        <div>
            <label for="AgeInput">Age Input</label>
            <input id="AgeInput" name="age" type="number">
        </div>
        <div>
            <label for="PasswordInput">Password Input</label>
            <input id="PasswordInput" name="password" type="password">
        </div>

    <!-- Knappen som sätter igång JS skriptet, ID så att man kan targeta ifrån JS-->
        <button onclick="addToArray()" id="button">Submit</button>


   
</body>
</html>

Can I use variables within the data in vue.js

// common.types
export const COMPONENT_TYPES = { TIME: "TIME" }

// App.vue
data: () => ({
  componentType: COMPONENT_TYPES.TIME
}) 

Sometimes undefined issues occur at very small frequencies. It’s only like that in safari.

Below is an error message….

undefined is not an object (evaluating ‘constants_design_types__WEBPACK_IMPORTED_MODULE_0_[“COMPONENT_TYPES”].TIME’)

Monaca Onsen UI copy image locally

I am retrieving data from a web service that includes images using HTTPRequest within Onsen UI.

I believe it’s best practise to try to bring the server images into the user’s device to save having to load the image from the server each time the page is displayed (especially for comment avatar files etc).

I’ve looked at PWA processes but I don’t intend for the app to be used offline and examples just refer to known JS, CSS, HTML files.

The method I’m considering is to be given the filename via the API, check if the file is saved locally and use it if found, if not then copy the file from the server to the device first before using it.

What is the most efficient (or best practise) solution to achieving this?

Thanks.

Make a new object using two different object in JavaScript

I have two objects. I am trying to do like :

var obj1 = {
 abc_name: "Jack", 
 abc_age: 24
}

var obj2 = {
 xyz_name: "Mike", 
 xyz_age: 22
}

Expected Output be like :

var obj = [{
 fieldName: "Name", 
 abc_name: "Jack", 
 xyz_name: "Mike"
}, 
{
 fieldName: "Age", 
 abc_age: 24, 
 xyz_age: 22
}]

I am trying with the nested for-in loop. But not getting expected results. Any better solution or idea ? Thanks in advance

Using array map on returned value from promise

I’m writing an async thunk in Redux to fetch Reddit posts, then map through the returned array to fetch each post’s comments and add them to the new object.

export const fetchPosts = createAsyncThunk("posts/fetchPosts", async ({ name, filter }) => {
    const data = await Reddit.getPosts(name, filter).then(async (val) => {
        const posts = await val.map(async (post) => {
            const comments = await Reddit.getComments(post.subreddit, post.id).then(val => {
                return val;
            });
    
            return { ...post, comments: comments };
        });
        
        return posts;
    });

    return data;
});

However, when the thunk is run in my app, an error occurs because the promises are still pending in the returned data object. How can I rectify this?

How to keep npm dependency in non minified form

I am trying to debug an issue in my repository which uses an npm package as a dependency (let’s call it ‘somedep’). Now somedep is owned by another team in my organization which uses rollup to minify and publish the package which we then consume for our repository. Now there’s a bug which I’m trying to debug. I can’t seem to debug it efficiently because the code from somedep is minified. I have access to the source code (the git repo) of somedep. Is there any way for me to connect my local copy of somedep to my package?

I want it connected in a non minified form.

Apply auth changes that affect to session and react parent component

I’m going to do my best to explain my problem here, but it’s going to be challenging so bear with me.

I have a web app developed in react + firebase with firebase authentication, the login is for now only handled with the mail and password provider. I’m using react router and firebase 9.

When someone logs in or out the auth token is persisted in session storage, and I have a condition in the App component (the first layer on my page) that shows a log in/register link if the user isn’t logged in and a my account link if the user is logged in. The problem is that I need to reload the page to see the changes, When logging in you get redirected to another route, but being a react app it doesn’t reload the whole page.

My App.js

  const auth = getAuth();
  const App = () => {
  const [user, setUser] = useState();
  const [expanded, setExpanded] = React.useState(true);
  const [activeKey, setActiveKey] = React.useState('1');

  const handleLogout = () => {
    signOut(auth).then(()=> {
      setUser({});
      sessionStorage.clear();
      console.log("unset user");
    }).catch((err) => {
      console.error(err);
      alert(err.message);
    })
  };

  onAuthStateChanged(auth, (user) => {
    if (user) {
      setUser(user)
      sessionStorage.setItem("user", JSON.stringify(user))
      const uid = user.uid;
      console.log("set user")

    } else {

    }
  });

    useEffect(() => {
      const loggedInUser = sessionStorage.getItem("user");
      if (loggedInUser != null) {
        const foundUser = loggedInUser.toString();
        setUser(foundUser);
        console.log(user)
      }
    }, []);
    return (
      <div>

              <li className="nav-item">
                {
                  (sessionStorage.user ?
                    <div className="d-flex justify-content-around row">
                      <Link className="nav-link" to="/user/perfil">Mi cuenta</Link>
                    </div>
                    : <Link className="nav-link" to="/login">Iniciar sesión / Registrarse</Link>
                  )
                }

          </li>
  </div>
)

}

export default App;

My login.js

const auth = getAuth();
console.log(auth.currentUser);
const loginWithEmailAndPassword = async (email, password) => {

setPersistence(auth, browserSessionPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)

    }).catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        alert(error.message)
    })
}

class Login extends Component {
constructor() {
    super();
    this.state = {
        email: "",
        password: "",
        redirect: "",
    };
}
handleChangeEmail = () => {
    this.setState({ email: document.getElementById("email").value });
    console.log(this.state);
}
handleChangePassword = () => {
    this.setState({ password: document.getElementById("password").value })
}
handleRedirect = () => {
    this.setState({ redirect: "/aplicacion" });
    console.log(this.state);
}
handleClick = async () => {
    try {
        await loginWithEmailAndPassword(
            this.state.email,
            this.state.password
        );
        this.handleRedirect();
    } catch (err) {
        console.error(err);
        alert(err.message);
    }
};
render() {

    if (this.state.redirect) {
        return <Navigate to={this.state.redirect} />
    }
    return (
        <div className="d-flex justify-content-center" >
                                    <div className="col-6">
                                        <Link to='/recuperacion' className="tiny-text">He olvidado mi contraseña</Link>
                                    </div>
        </div>
    )
}

}

Amazon S3 Image is not working on og:image tags though bucket is public

Please give me some pointers for solving the issue which is listed below.

I have an issue on og tags for fetching the image. I am using the React with Razzle for server side rendering. All the site images is stored on aws bucket which has public access on for fetching the image.

These are the tags which I am using under the specific page through Helmet.

<Helmet>
          <title>{this.props.data.title+" | by "+this.props.data.username} </title>
          {/* facebook open graph tags */}
          <meta data-rh="true" property="og:locale" content="en_US" />
          <meta data-rh="true" property="og:url" content="http://somedomain.com/view/Some title of the post" />
          <meta data-rh="true" property="og:title" content="Some title of the post" />
          <meta data-rh="true" property="og:type" content="article" />
          <meta data-rh="true" property="og:description" content="Description of the post" />
          <meta property="og:image" content="https://s3.ap-south-1.amazonaws.com/bucketname/somerandomnameofimage.png" />
          <meta property="og:site_name" content="SiteName" />  
        </Helmet>

After some findings I have changed the image from some random link which is accessible and use that url of image under the og:image tags and then I checked and its working.

What I am thinking is it will not fetch the aws s3 image. But if that is the case then how other people do.

I checked many sites og tags and found that they will use some subdomain.domain.com/someimagename.extension, If this is the only case then how I achieve this. And my question is then why we use image hosting provider if we have to do it like the ancient programming way.

Please suggest me how to solve this.
Any help or suggestion is really appreciated.

ms access db connection in node.js

I am trying to connect to an Access database with nuintun’s node-adodb package. I have successfully connected to it in my laptop @ home and created a dist. package to install it to my computer @ office. However after installing it to my office laptop, I am getting below error message during connection to access database.

connection string:
"Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=C:\Temp\Mdb.mdb;Persist Security Info=False;"

error message:
Error: Spawn C:WINDOWSSysWOW64cscript.exe error

I tried several connection configs to solve this but cannot get it done.

With this method (connection = ADODB.open(dbConn);) I am getting above error message.

With this connection = ADODB.open(dbConn, true) or this connection=ADODB.open(process.arch.includes('64') or this connection = ADODB.open(connection, 'x64') I am getting below error message:

Error: Spawn C:WINDOWSSystem32cscript.exe error

Any help appreciated.