Canvas drawing scaling when height changing

I have problem with canvas. I want canvas full height its working. But when i drawing a circle and i put some space in div then the circle is scaling very bad. scaled circle. I want circle stay where it was drew when i put some space in div. Here is my code. Please help me to find the solution. Thanks. If u test it first add some space in div and there you can draw.

https://jsfiddle.net/gu3w97zf/

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let coord = { x: 0, y: 0 };

document.addEventListener('mousedown', start);
document.addEventListener('mouseup', stop);
window.addEventListener('resize', resize);

function resize() {
  ctx.canvas.width = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
}

resize();

function start(event) {
  document.addEventListener('mousemove', draw);
  reposition(event);
}

function reposition(event) {
  coord.x = event.clientX - canvas.offsetLeft;
  coord.y = event.clientY - canvas.offsetTop;
}

function stop() {
  document.removeEventListener('mousemove', draw);
}

function draw(event) {
  ctx.beginPath();
  ctx.lineWidth = 5;
  ctx.lineCap = 'round';
  ctx.strokeStyle = '#ACD3ED';
  ctx.moveTo(coord.x, coord.y);
  reposition(event);
  ctx.lineTo(coord.x, coord.y);
  ctx.stroke();
}
.all {
      background: gray;
    position: relative;
    min-height: 100%;
    letter-spacing: 50px;
}

.text {
  position: inherit;
  min-height: 100%;
    z-index: 99;
    width: -webkit-fill-available;
}

#canvas {
  width: -webkit-fill-available;
    position: absolute;
    height: -webkit-fill-available;
    top: 0;
    z-index: 10;
}
<div class="all">
<canvas id="canvas">
  
</canvas>
<div contenteditable="true" class="text">

</div>
</div>

Weather app, how to write this function better? [closed]

Making the weather app and this is what ive built so far

const obj = {}

async function weather(city) {
    try {
        let response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=fe0199b3b09ac84b46e6413bc44a3a3f`, {mode: "cors"})
        let data = await response.json();

        obj["Weather"] = data.weather
        obj["Location"] = data.name
        obj["Temperatures"] = data.main
        obj["Wind"] = data.wind
        
    } catch (err){
        console.error(err)
    }

}

weather("London")

Based on these instructions: Weather app

Please tell me how to improve!!!!

Cannot find module ‘D:..servernode_modulessequelizetypesutils’

I am coding a React app in VS code and I had run it multiple times, everything was working great, and when I ran npm start another time, the server crashed and gave me this error. I hadn’t changed anything in my code, one minute it was working and then the other not. I’ve tried deleting node modules, package-lock.json, but nothing works. Does anyone have any idea? I didn’t know what snippets of code, if any, I should include, so please tell me.

Passing class method as callback to another class in javascript

I am trying to create a pop up menu (via a class) called from another class. After these inputs are filled in I want the input data to be processed by the object from which the pop up menu was initiated.

My thought process created the following code (simplified ofc):

class foo{
        constructor(){
            this.prroperty = 'yes';
        }

        eventMethod(){
            let eventForm = new bar();
            eventForm.fire(this.endMethod);
        }

        endMethod(values){
            // console.log(this);
            console.log(values + this.prroperty);
        }
    }

class bar{
    constructor(){
        this.property = 'no';
    }

    fire(callback){
        let value = 'message';
        callback(value);
    }
}

let object = new foo();
object.eventMethod();

this doesn’t work obviously because “this” now no longer referes to the foo created object.
I’m planning on using the controller from the foo class and the popup menu created by the bar class a lot. Therefore I’m using classes instead of creating single objects.

My question is if there is a way to deliver and process the values while still being able to do so within classes instead of objects because i want to use them multiple times.

How to make a simple calculation in HTML & JS with internal values

Good evening everyone,

I am trying to make an html email using a CRM that has a total price which i get from {total_price}
and a deposit 50% of the total price.
As there is no {deposit} in the CRM i am using , i though i would make a simple calculation

<!DOCTYPE html>

<html>
<p id="deposit"></p>
<script>

var x={total_price};
var y=0.5;
var  z=x*y;

document.getElementById("deposit").innerHTML = "Deposit : " + z + "€";
</script>

But my CRM doesn’t seem to be able to handle JS, is there any other way to have the same result?

FirebaseCloudFunctions only returns null

I am trying to get a response from a Firebase cloud function, but the only thing I get back is null. The console output shows that the fetch command works and outputs the correct data.

exports.create = functions.https.onCall((data, context) => {
fetch("https://mywebsite.com/x", {
    method: "POST",
    headers: {
        "Authorization": "Bearer MyKey",
        
    },
    body: JSON.stringify({"myData":data.myData})
}).then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
        
        
      });
      return data.json();
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

});

I tried using Promise, I tried returning is as json and just as return data nothing seems to work. The result is always null

The code I use to call it in my flutter app:

HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('create');
    final response = await callable.call(<String, dynamic>{
      'myData': 'data',
      
    }).then((value) => print(value.data));

Having Issues with Flexbox

Trying to create dynamic react-mdl cards with specific height and widths. The problem is coming from a float being longer than the width of the card it is in. How can I fix the float or containers to allow cards equally spaced and dynamically sized on each row.

Here is the current code for the container and card
HTML

  <Card className="card">
    <CardTitle className="card-title">
      <img className="item-image" src={icon} alt={alt}/>
    </CardTitle>
    <CardText className="card-text">
      <div>Id: {id}</div>
      <div>Quantity to buy: {quan}</div>
      <div>Total Profit: {profit}</div>
    </CardText>
  </Card>

CSS

.itemlist {
    background-color: rgb(211, 208, 208);
    position: relative;
    border: 2px solid red;
    width: 50%;
    height: 100%;
    float: left;

    display: flex;
    flex-wrap: wrap;
    overflow-x: hidden;
    overflow-y: auto;
}

.card {
    display: flex;
    width: auto;
    height: auto;
    border: 2px solid black; 
    background: green;
    margin: 0 10px;
}

.card-title {
    height: 100px;
    color: #fff;
    background: red;
    justify-content: center;
    align-items: center;
}
.item-image {
    width:auto;
    height:auto;

}[enter image description here][1]

Axios – transformResponse, parsing JSON and proper error handling

I am learning axios! What I am trying to achieve is GET with converted reply.

I am trying like this:

const getUser = async (request: Request) =>
    axios.get(`api/v1/user/1`, {
        convertUser: (data: string) => {
            return data ? convertUser(JSON.parse(data)) : data;
        }
    });
const convertUser = (data: User): ConvertedUser => {
    const convertedUser: ConvertedUser  = {
    // some convertion here
    return convertedUser;
};
interface User {
    userId: string;
    userName: string;
}

but.. when response is not User, but some kind of error – like “404”, I got an error and everything goes wrong.

where should I parse this data? how could I achieve error handling in this function? because when I am converting it – I am losing info about status error code and message.

How to imperatively handle an error, with react-query?

Being that react-query is heavily based on the declarative approach, the error handling I see in all examples looks something like this:

function Todos() {
   const { isLoading, isError, data, error } = useQuery('todos', fetchTodoList)
 
   if (isLoading) {
     return <span>Loading...</span>
   }
 
   if (isError) {//If there is an error, render different JSX
     return <span>Error: {error.message}</span>
   } 
   
   return (
     <ul>
       {data.map(todo => (
         <li key={todo.id}>{todo.title}</li>
       ))}
     </ul>
   )
 }

But what if I want to just show an alert, in case of an error? Or perhaps, i’m using some error handling interface, that has an imperative trigger? Something like this:

if (isError) alert(`An error has occurred: ${error.message}`)

In this case, I get two alerts. Something causes the component to re-render, which of course leads to “duplicate” error handling.

Why is this important to me? Because my error handling logic might not be based on rendering some specific JSX within my component, but rather on some manual one-time trigger. The alert is just a basic example.

Any suggestions will be greatly appreciated!

Reactivity of primitives using reactive in Vue 3

According to the docs, primitives shouldn’t become reactive when using reactive wrapper, that’s why in this case we should go with ref. The same situation is when we want to reassign the entire object instead of mutating it.

My question is why in the following snippets counter2 and state2.counter start working correctly when we uncomment the commented lines?

<script setup>
import { ref, reactive } from 'vue';
  
let counter1 = ref(0);
let counter2 = reactive(0);
  
const increment = () => { 
  // counter1.value++;
  counter2++;
}
</script>

<template>
  <h3>counter1 {{ counter1 }}</h3>
  <h3>counter2 {{ counter2 }}</h3>
  <button @click="increment">increment</button>
</template>
<script setup>
import { ref, reactive } from 'vue';
  
let state1 = ref({ counter: 0 });
let state2 = reactive({ counter: 0 });
  
const increment = () => { 
  // state1.value = { counter: state1.value.counter + 1 };
  state2 = { counter: state2.counter + 1 };
}
</script>

<template>
  <h3>counter1 {{ state1.counter }}</h3>
  <h3>counter2 {{ state2.counter }}</h3>
  <button @click="increment">increment</button>
</template>

ReactJS + NextJS – How to pass props from _app.js to page?

I just switched from ReactJS to NextJS and I can’t find how to pass props from _app.js to a page.

I’m trying to call a function in _app.js from a different page. In ReactJS it was straight forward, since you had to make your own Router, you could just pass props from App.js down to the pages. Now in NextJS I’m not explicitly calling the page, so I can’t pass the props anywhere.

What is the way to do it in NextJS?

On AntD Select change Runtime Error occurs when Navigating to another page

Below contains my form page – form.tsx which has a sample form.

After a selection is made from the antd Select form items below and I navigate to another page the following error comes up:

TypeError: Cannot read properties of null (reading 'removeEventListener')

please let me know your thoughts on this.

const FormPage: NextPage = () => {
  const onFinish = (values: any) => {
    console.log(values);
  };

  return (
    <div>
      <Card>
        <Row align="middle" gutter={10} style={{ marginTop: 50 }}>
          <Col sm={16} xl={12}>
            <Form
              {...antlayout}
              name="nest-messages"
              onFinish={onFinish}
            >
              <Form.Item name="Gender" label="Person">
                <Select
                  showSearch
                  placeholder="Select a person"
                >
                  <Option value="jack">Jack</Option>
                  <Option value="lucy">Lucy</Option>
                  <Option value="tom">Tom</Option>
                </Select>
              </Form.Item>

              <Form.Item wrapperCol={{ ...antlayout.wrapperCol, offset: 8 }}>
                <Button type="primary" htmlType="submit">
                  Submit
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export const getStaticProps = async () => {
  return {
    props: {
      layout: 'master',
      name: '',
      title: 'Form Page',
    },
  };
};

export default FormPage;

Object properties are undefined even it show up in the console log

I am using react-query useMutation in order to call the api and get the response. I am trying to read an array inside the response object. But it is undefined even response can be logged using console log.

This is my useMutation function.

const { mutate, isLoading, data={}, error={} } = useMutation(redeemTicket, {
onSettled: (successData, err) => {
  if (successData && !successData.error) {
    setIsRedeemSuccess(true)
    analytics().logEvent('redemption_success', {
      type: 'scan',
      eventId: selectedEvent.id,
    });
  } else {
    setIsRedeemSuccess(false)
    analytics().logEvent('redemption_failed', {
      error: successData?.error || err?.error || err?.message,
      type: 'scan',
      eventId: selectedEvent.id,
    });
  }
},

});

These are my sample logs.

const scannedData = data?.scanned;
console.log("========================data ", data); // {"scanned":[{"id":1629,"assetId":205042,"redeemStatus":0,"redeemMediaUrl":"https://api.test-yh.io/api/getPubFile?id=1304","section":"3","rowNo":"H2","seatNo":"20","category":"",}],"count":1}
console.log("========================scannedData ", scannedData); // undefined

Can anyone help me on this?