SSR with NextJS not working for some pages

I have just deployed a nextjs application with Vercel. Everything works fine but I’m having some issues with SSR. I have two pages, the index / homepage and one registration page.

When I check the source code for the registration page I can see all the content (SSR working fine) but when I check for the homepage, it looks like it is being rendered by the client (can’t see the content).

Does anyone know what may be causing this behavior?

ngModel does not work on modal page in Ionic 6

I am developing an Ionic/Angular app and wanted to use ngModel as alwayls. I am opening a modal from a modal and then want to use it like:

<ion-list>
<ion-item>
  <ion-label position="stacked">Name des Rezepts</ion-label>
  <ion-input [(ngModel)]="model" ></ion-input>
</ion-item>
</ion-list>
<ion-button (click)="save()">Save</ion-button>

i declared the variable in typescript like:

public model="";

But when i click save, my output IS ALWAYS the empty string?!

I imported ReactiveFormsModule in my app.module.ts and on normal pages it works, but in modals it seems like that it does not work?!

Do you guys have any ideas?
Thank you!

vue client side axios router

i’m trying to get vue-router to work with blogger feeds json api, i managed to make it work but on reload it goes back to the first page, i tried to add html components and template in routes parameter but it did not work, i tried everything i begun to wonder if it is even possible, here is my code:

  new Vue({
    el: '#app',
    router: new VueRouter({}),
    vuetify: new Vuetify({}),
    data() {
      return {
        feedAPI: '/feeds/posts/default?alt=json&start-index=',
        items_all: [],
        items: [],
        Totalposts: null,
        Totalpages: null,
        Startindex: 1,
        pageNumber: null,
        keyword: '',
        results: [],
        Postsperpage: 5,
      }
    },
    methods: {
      getPosts() {
        axios.get(this.feedAPI + this.Startindex + '&max-results=' + this.Postsperpage).then(async (response) => {
          const items = await response.data;
          this.items_all = items.feed;
          this.items = this.items_all.entry;
          var totalPosts = this.items_all.openSearch$totalResults.$t;
          this.Totalposts = totalPosts;
          var itemsPerPage = this.items_all.openSearch$itemsPerPage.$t;
          this.Postsperpage = itemsPerPage;
          var totalPages = Math.ceil(this.Totalposts / this.Postsperpage);
          this.Totalpages = totalPages;
          this.$router.push({
            query: Object.assign({}, this.$route.query.pageNumber, {
              page: this.pageNumber || 1
            })
          });
          this.$nextTick(() => {
            this.pageNumber
          });
        })
      },
      onPageChange() {
        this.Startindex = Math.ceil((this.pageNumber * this.Postsperpage) - (this.Postsperpage - 1));
        this.getPosts();
      },
      top() {
        window.scrollTo({
          top: 0,
          behavior: 'smooth'
        });
      },
      getResults() {
        if (this.keyword.length > 2) {
          axios.get("/feeds/posts/default?alt=json&q=" + this.keyword).then(res => (this.results = res.data.feed.entry)).catch(err => console.log(err));
        }
      }
    },
    watch: {
      keyword: function(newVal) {
        if (newVal.length > 3) {
          this.getResults();
        }
      }
    },
    computed: {},
    created() {
      this.getResults()
    },
    mounted() {
      this.getPosts();
    }
  });

for the html :

          <v-text-field v-model="keyword" @input="getResults" placeholder="Type to Search"></v-text-field>
          <div v-if="getResults">
            <span v-for="result in results">
              <a v-for="i in result.link" v-if="i.rel == 'alternate'" :href="i.href" :title="result.title.$t" v-html="i.title"></a>
              <br />
            </span>
          </div>
<div v-for="item in items">
<h3><a v-for="i in item.link" v-if="i.rel == 'alternate'" :href="i.href" :title="item.title.$t" v-html="i.title"></a></h3>
</div>
<v-pagination v-model="pageNumber" :length="Totalpages" @input="onPageChange" prev-icon="mdi-menu-left" next-icon="mdi-menu-right" v-on:click.native="top"></v-pagination>

what causes this error on the 17th line? the program says: Unexpected token ‘m’ at 17:24 “xpath=//[@id=”messageBoxInline”]/div/div/span/span[2]/a”,

{
  "Name": "Koniki kwater 60 dni",
  "CreationDate": "2022-2-22",
  "Commands": [
    {
     "Command": "label",
      "Target": "SEKWENCJA",
      "Value": "",
      "Description": ""
    },
    {
      "Command": "clickAndWait",
      "Target": "linkText=Zarejestruj swojego konia",
      "Value": "",
      "Targets": [
        "linkText=Zarejestruj swojego konia",
        "xpath=//[@id="messageBoxInline"]/div/div/span/span[2]/a",
        "xpath=//span/span[2]/a",
        "css=#messageBoxInline > div > div > span > span:nth-child(2) > a"
      ],
      "Description": ""
    },
    {
      "Command": "clickAndWait",
      "Target": "linkText=60 dni",
      "Value": "",
      "Targets": [
        "linkText=60 dni",
        "id=agi-210999506001623065739",
        "xpath=//[@id="agi-210999506001623065739"]",
        "xpath=//a[@id='agi-210999506001623065739']",
        "xpath=//span[9]/a",
        "css=#agi-210999506001623065739"
      ],
      "Description": ""
    },
    {
      "Command": "clickAndWait",
      "Target": "xpath=//[@id="agi-220949427001623065756"]/span/span/span",
      "Value": "",
      "Targets": [
        "xpath=//[@id="agi-220949427001623065756"]/span/span/span",
        "xpath=//td[10]/button/span/span/span",
        "css=#agi-220949427001623065756 > span > span > span"
      ],
      "Description": ""
    },
    {
      "Command": "clickAndWait",
      "Target": "id=nav-next",
      "Value": "",
      "Targets": [
        "id=nav-next",
        "xpath=//*[@id="nav-next"]",
        "xpath=//a[@id='nav-next']",
        "xpath=//a[2]",
        "css=#nav-next"
      ],
      "Description": ""
    },
    {
      "Command": "gotoLabel",
      "Target": "SEKWENCJA",
      "Value": "",
      "Description": ""
    }
  ]
}

How to de-normalize numbers (reverse normalize) in javascript?

I have a function thats giving me a number between 0 and 1, for the x
and i also have another function thats giving me a number between 0 and 1, for the y coordinate

then i want to visualize it using canvas, so i would want to turn the numbers into pixel values

for example:

i have a a canvas thats 300x400px,
if the normalized number is 0.5, for the x and the y

what math would i need to do to make it 150x, 200y?

my code to visualize it (this part works, its just for refrence)

ctx.beginPath()
ctx.arc(xval, yval, 5, 0, 2 * Math.PI)
ctx.fillStyle = "#FF0000";
ctx.fill()

ctx.beginPath();
ctx.moveTo(0, xval);
ctx.lineTo(300, xval);
ctx.stroke();

ctx.beginPath();
ctx.moveTo(yval, 0);
ctx.lineTo(yval, 400);
ctx.stroke();

thanks!

how to console.log in react-simple-chatbot

i try to do a bot who works as i want but i would like to implement some features (send mails, popups etc..) but i don’t understand how can i console.log any elements .

there is my code:

import React from "react";
import ChatBot from "react-simple-chatbot";
import props from 'prop-types';

function Sendemail() {

  console.log("test")
}
function CustomChatbot(props) {
  const config = {
    width: "300px",
    height: "400px",
    floating: true
  };

  return <ChatBot steps={steps} {...config} />;
 }
export default CustomChatbot;

const steps = [
  {
     id: "Greet",
     message: "Hello, Welcome to our website",
     trigger: "Ask Name",
  },
  {
     id: "Ask Name",
     message: "Please type your name?",
     trigger: "Waiting user input for name"
  },
  {
     id: "Waiting user input for name",
     user: true,
     trigger: "ask questions"
  },
  {
     id: "ask questions",
     message: "Hi {previousValue}, I am Tony the bot, How can i help you!",
     trigger: "informations"
  },
  {
     id: "informations",
     options: [

                { 
                  value: "Who founded Babycare",
                  label: "Who founded Babycare",
                  trigger: "Who founded"
                },
                {
                  value: "Contact",
                  label: "Contact",
                  trigger: "Contact"
                }
                
              ]
  },
  {
     id: "Who founded",
     message: "ERWAN",
     trigger: "informations"
  },




  {
     id: "Contact",
     message: "Ok, first, enter your adress-mail",
     trigger: "Ask email"
  },
  {
     id: "Ask email",
     user: true,
     trigger: "get-email"
  },

  {
    id: "get-email",
    message: "ok, {previousValue} !! Type your value now, please be fair",
    trigger: "your question"
  },

  // {
  //   id: "your question",
  //   message: "Ok. Now, enter your message to the staff. Please be fair !!",
  //   trigger: "your message"
  // },
  {
    id: "your question",
    user: true,
    trigger: "send mail"
  },

  
  {
    id: "send mail",
    message: "ok,  there is your message : {previousValue} !! The support team will answer you as possible",
    
    trigger: "thelast"
  },

  
  {
    id: "thelast",
    component: (
      <div> {Sendemail()} </div>
    ),
  
    end: true
  },


  
];

THis code is my last try, on the last proposition, i just tried to put my function Sendmail() in the id:”the last”. But i can’t call function in array. I am quite lost, how can i do that?

Thanks for yours answers!

Full screen canvas without messing up collisions

I want to make a game fullscreen but when I do the click collisions are messed up, here is how things behave…

function fullScreen() {
    if(canvas.webkitRequestFullScreen) {
      canvas.webkitRequestFullScreen();
    } else {
      canvas.mozRequestFullScreen();
      }
}
var button = {
    x:20,
    y:60,
    width:50,
    height:50
}

I have an event listener that listens for a click and checks if we have clicked the button using the mouse and buttons coordinates. However when we change the canvas size in the full-screen function, the coordinates are messed up and not exact with what the user is seeing, how do I fix this and align the coordinates no matter the size of the canvas?

Test react router with testing library and jest

I am trying to test react-router with react testing library / jest, how would I test the following with correct coverage? using react-router-dom 5.2.0

Routing component

   <BrowserRouter>
          <Header links={Items} />
          <div className="App">
            <Switch>
              <Route exact path="/">
                <Redirect to="/home" />
              </Route>
              <Route exact path={["/home", "/"]} component={home} />
              <Route path="/brochure/:id" render={(props: RouteComponentProps<any>) => <Brochure {...props} />} />
              <Route exact path="/detail" render={() => <Details />} />
              <Route component={NotFound} />
            </Switch>
          </div>
       </BrowserRouter>

Test

I have done the following:

it('Should render routing', () => {
    const history = createMemoryHistory()
    render(
      <Router history={history}>
        <Routing />
      </Router>,
    )
    expect(screen.getByText(/Home/i)).toBeInTheDocument()
    expect(screen.getByText(/Details/i)).toBeInTheDocument()
  });

This passes, but it’s not really testing it properly? Any idea’s

JavaScript onlick not working on browser but working perfectly in w3school tryit editor

please i need help, i copied some codes from w3school which works perfectly in their tryit editor but not working in my browser

this is the code

<div class="w3-sidebar w3-bar-block w3-border-right" style="display:none" id="mySidebar">
  <button onclick="w3_close()" class="w3-bar-item w3-large">Close &times;</button>
  <a href="#" class="w3-bar-item w3-button">Link 1</a>
  <a href="#" class="w3-bar-item w3-button">Link 2</a>
  <a href="#" class="w3-bar-item w3-button">Link 3</a>
</div>

<!-- Page Content -->
<div class="w3-teal">
  <button class="w3-button w3-teal w3-xlarge" onclick="w3_open()">☰</button>
  <div class="w3-container">
    <h1>My Page</h1>
  </div>
</div>

<img src="img_car.jpg" alt="Car" style="width:100%">

<div class="w3-container">
<p>This sidebar is hidden by default, (style="display:none")</p>
<p>You must click on the "hamburger" icon (top left) to open it.</p>
<p>The sidebar will hide a part of the page content.</p>
</div>

<script>
function w3_open() {
  document.getElementById("mySidebar").style.display = "block";
}

function w3_close() {
  document.getElementById("mySidebar").style.display = "none";
}
</script>

Post back stop working inside update panel control

After I load few JavaScript files inside a master page the post back is not working that is found inside an update panel. The post back works fine without the javascripts loaded.

    <script type="text/javascript" src="<%# Page.ResolveUrl("/popper/popper.min.js") %>"></script>
    <script type="text/javascript" src="<%# Page.ResolveUrl("/anchorjs/anchor.min.js") %>"></script>
    <script type="text/javascript" src="<%# Page.ResolveUrl("/is/is.min.js") %>"></script>
    <script type="text/javascript" src="<%# Page.ResolveUrl("/fontawesome/all.min.js") %>"></script>
    <script type="text/javascript" src="<%# Page.ResolveUrl("/lodash/lodash.min.js") %>"></script>
    <script type="text/javascript" src="<%# Page.ResolveUrl("/list.js/list.min.js") %>"></script>
    <script type="text/javascript" src="<%# Page.ResolveUrl("/assets/js/theme.js") %>"></script>```

React.js: Fetching Data from API with Bearer Token

I am building a React.js SPA, that receives data from an API with Bearer Token Authentication (so a fetch request for authentication has to be done first and the given token can be used temporarily to access the data until the auth session ends)

I can authorize and print the object to the console, but the object is not saved into the variable objectOutput in order to be accessed by the components below.

My thought is, that the asynchronous fetching causes this, and the components are rendered before the fetch() reslut has arrived. But I wonder how this could be fixed, so I can store it in the variable and the components can access the data as their props.

Thanks in advance 🙂

import Header from "./components/Header";
import Cardsection from "./components/Cardsection";
import Flagsection from "./components/Flagsection";
import Footer from "./components/Footer";
import MapChart from "./components/MapChart";
import { useEffect } from "react";

let api_url = "https://api-url:3000";
let batch_id = "XXX";
let api_token = "";
let objectOutput = "";

function App() {
  useEffect(() => {

    const authorize = async () => {
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");

      var raw = JSON.stringify({
        username: "username",
        password: "password",
      });

      var requestOptions = {
        method: "POST",
        headers: myHeaders,
        body: raw,
        redirect: "follow"
      };

      const res = await fetch(api_url + "/auth", requestOptions).catch(console.log("error"));
      const data = await res.json();
      api_token = data.token;
      console.log("Successful Authorization. Token: " + api_token);

      const getObject = async () => {
        var myHeaders = new Headers();
        myHeaders.append("Authorization", "Bearer " + api_token);

        var requestOptions = {
          method: "GET",
          headers: myHeaders,
          redirect: "follow"
        };

        const res = await fetch(api_url + "/get?function=readObject&args=" + batch_id, requestOptions).catch(console.log("error"));
        const data = await res.json();

        objectOutput = data;
        console.log(data);

      
      };
      getObject()

    };

    authorize();

  }, []);

  return (
    <div className="App">
      <Header
        title="Lorem Ipsum"
        description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
      />
      <Flagsection hasFlag={objectOutput.alarmFlag} />
      <Cardsection sort={""} treatment={""} plantheight={""} harvesttime={""} />
      <MapChart/>
      <Footer />
    </div>
  );
}

export default App;```

Vue3 LocalStorage set after component render

I have a nav bar that loads user data, all of this happens after a user successfully logs into the application. The problem is, localStorage must be setting slightly after I load the nav bar. If I wrap it in a setTimeout() everything works but I would rather my variables be reactive in nature since they can change based on user activity.

Toolbar.vue

<template>
  <!--begin::Toolbar wrapper-->
  <div class="d-flex align-items-stretch flex-shrink-0">
    <h2>check for value</h2>
    <div v-if="activeAccountId">{{activeAccountId}}</div>
  </div>
  <!--end::Toolbar wrapper-->
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";

export default defineComponent({
  name: "topbar",
  data() {
    let activeAccountId = ref(JSON.parse(localStorage.getItem('activeAccountId') || '{}')).value;

    return {
      activeAccountId
    }
  }
});
</script>

I’ve tried using watchers, and using setup() verses data(), but nothing seems to work properly. As I mentioned, setTimeout() does work but I’d rather avoid manually triggering a timeout and let vue handle things how it wants to.

Here’s a simple example, I can’t setup a dummy code side since it won’t have the localStorage item set.

Trouble promisifying setInterval to do an action continuously for a given period and then allow a new asynchronous function to begin

Having trouble promisifying setInterval. The .then() is occurring immediately despite the embedEditor function returning a promise only if time === 0. How do I make a function in setInterval return a promise once a time period has completed?

const interval = setInterval(embedEditor, 1000);
async function embedEditor() {
    time -= 1;
    //inner function....//
    if (time === 0) {
        clearInterval(interval);
        return new Promise((res) => { res("time period over"); });
    }
}
await interaction.reply({ embeds: [exampleEmbed], components: [row, row2] });
await interval
    .then(/*action*/);

iam getting buffer and hex codes

var fs = require('fs');

fs.readFile('TestFile.txt', function (err, data) {
                    if (err) throw err;

    console.log(data);
});

//TestFile.txt This is test file to test fs module of Node.js

  1. Iam getting buffer and hex codes in place of console data
  2. <Buffer 54 68 69 73 20 69 73 20 74 65 73 74 20 66 69 6c 65 20 74 6f 20 74 65 73 74 20 66 73 20 6d 6f 64 75 6c 65 20 6f 66 20 4e 6f 64 65 2e 6a 73>