Marker not showing @react-google-maps/api

I’m aware there are similar questions to this… but nothing has answered my question

I’m trying to add a marker to my google map but it is not showing up heres my component

import { React, useMemo } from "react";

import { GoogleMap, Marker, useJsApiLoader } from "@react-google-maps/api";

import MapContainerStyles from "./styles/MapContainerStyles";

const Map = () => {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: API_KEY,
  });

  const center = useMemo(() => ({ lat: -30.292038, lng: 153.118896 }), []);

  const onLoad = (marker) => {
    console.log("marker: ", marker);
  };


  const options = {
    mapTypeControl: false,
    streetViewControl: false,
    fullscreenControl: false,
  };

  if (!isLoaded) return <div>Loading...</div>;

  return (
    <MapContainerStyles>
      <GoogleMap zoom={15} options={options} center={center} mapContainerClassName="map-container">
        <Marker onLoad={onLoad} position={center} />
      </GoogleMap>
    </MapContainerStyles>
  );
};

export default Map;

The console logs for the markers onLoad return the following

enter image description here

There are no errors in the console

In case you need it my styled component is here

import styled from "styled-components";

const MapContainerStyles = styled.div`
  width: 100%;
  height: 208px;
  & .map-container {
    width: 100%;
    height: 100%;
  }
`;

export default MapContainerStyles;

I’ve looked at multiple resources and it appears as if I am doing everything correctly.. but the marker is just not showing

any help would be appreciated

How do I solve this error”Uncaught Error: [News] is not a component. All component children of must be a or “?

I am trying to make a news app and this version 6 of react-router-dom is not working.. can anybody tell me how to fix it?

import "./App.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import React, { Component } from "react";
import NavBar from "./components/NavBar";
import News from "./components/News";
export default class App extends Component {
  render() {
    return (
      <div>
        <Router>
          <NavBar />
          <Routes>
          <Route exact path="/"><News key="general" pageSize={this.pageSize} country="in" category="general"/></Route> 
          <Route exact path="/business"><News key="business" pageSize={this.pageSize} country="in" category="business"/></Route> 
          <Route exact path="/entertainment"><News key="entertainment" pageSize={this.pageSize} country="in" category="entertainment"/></Route> 
          <Route exact path="/general"><News key="general" pageSize={this.pageSize} country="in" category="general"/></Route> 
          <Route exact path="/health"><News key="health" pageSize={this.pageSize} country="in" category="health"/></Route> 
          <Route exact path="/science"><News key="science" pageSize={this.pageSize} country="in" category="science"/></Route> 
          <Route exact path="/sports"><News key="sports" pageSize={this.pageSize} country="in" category="sports"/></Route> 
          <Route exact path="/technology"><News key="technology" pageSize={this.pageSize} country="in" category="technology"/></Route> 
          </Routes>
        </Router>
      </div>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

React drag and drop not working as expected

I am making a restaurant reservation system and want my users to be able to add tables and place them on the canvas with drag and drop functionality. Now, When dragging the tables SLOWLY, it works, but as soon as it’s done fast, they all snap to 0 on x axis and 0 on y axis, so in top left corner of the canvas. My code is as follows:

  const onMoveLabel = (event) => {
    event.target.removeEventListener("click", onLabelClick);
    event.target.dataset.hasMoved = true;

    let moveX;
    let moveY;

    moveX = event.clientX;
    moveY = event.clientY;
    let minBoundX = 0;
    let minBoundY = 0;
    let maxBoundX =
      minBoundX + canvasRef.current.offsetWidth - event.target.offsetWidth;
    let maxBoundY =
      minBoundY + canvasRef.current.offsetHeight - event.target.offsetHeight;

    const labels = document.querySelectorAll<HTMLDivElement>(".label");
    labels.forEach((label: HTMLDivElement) => {
      if (overlaps.includes(parseInt(label.dataset.id as string))) {
        label.style.left =
          Math.max(
            minBoundX,
            Math.min(label.offsetLeft + moveX - startX, maxBoundX)
          ) + "px";
        label.style.top =
          Math.max(
            minBoundY,
            Math.min(label.offsetTop + moveY - startY, maxBoundY)
          ) + "px";
      }
    });

    startX = moveX;
    startY = moveY;
  };

Having trouble with displaying an image

The goal is to display an authenticated user’s avatar pic.
back-end and front-end have separate servers and are using restful api and i’m using vanilla js to send a GET request to get the avatar and show it.
this is what i return in laravel controller:

    return response()->file(base_path() . '/storage/app/images/avatars/1.jpeg', ['Content-Type' => 'Image/jpeg']);

    // also tryed these but no luck
    // return response()->download(Storage::disk('local')->get('images/avatars/1.jpeg'), 'name', ['Content-Type' => 'Image/jpeg']);

    // return Storage::disk('local')->get('images/avatars/1.jpeg');

    // return response()->file(Storage::disk('local')->get('images/avatars/1.jpeg'));

and this is how i set user’s avatar:

    Storage::putFileAs('images/avatars/', $request->avatar, $request->accountId, 'private');

and in front-end: (i’m new in front-end and with js)

let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
let myRequest = new Request('avatar');

let myHeaders = new Headers();
myHeaders.append("Accept", "application/json, text-plain, */*");
myHeaders.append("X-Requested-With", "XMLHttpRequest");
myHeaders.append("X-CSRF-TOKEN", token);
myHeaders.append("Content-Type", 'image/jpeg/jpg');

let init = {
    method: 'GET',
    mode: 'cors',
    credentials: 'same-origin',
    headers: myHeaders,
};

fetch(myRequest, init).then((response) => {
    console.log(response);
    return getBody(response);
}).then((data) => {
    console.log(data);
    createAppendElm('img', {
        'src': 'data:image/jpeg;base64,' + btoa(data),
        'alt': 'avatar'
    }, getElm('box'));
});


function createAppendElm(tagName, attributes, parentElm) {
    var elm = document.createElement(tagName);

    for (const attribute in attributes) {
        if (Object.hasOwnProperty.call(attributes, attribute)) {
            const value = attributes[attribute];

            elm.setAttribute(attribute, value);
        }
    }

    parentElm.appendChild(elm);

    return elm;
}

function getBody(response) {
    const contentType = response.headers.get("content-type");

    if (contentType && contentType.indexOf("application/json") !== -1) {
        return response.json();
    } else {
        return response.text();
    }
}

console.log(data) shows the binary content of the picture.(���� …)
any suggestions?

Is this BAD or GOOD duplicate code? and splitting Code [closed]

Hear me out first! I know duplicate code is bad, but I also read some text on “Functions should do one thing only”, that’s why I split them! Plus, there may be a case at some point, where I only need some of the split functions. What’s bothering me is, all my split functions have a little bit of duplicate code (as seen below). Can I somehow get rid of the loops and, like, put them in a function or something? Or am I doing something completely wrong?

Thanks in advance!

function updateUIAttributePoints() {
    updateUIAttributePointsClass();
    updateUIAttributePointsEditable();
    updateUIAttributePointsFinal();
}

function updateUIAttributePointsClass() {
    attributesJSON.forEach(curAttribute => {
        const curAttributeName = curAttribute.label;

        const classAttributeInput = document.getElementById(curAttributeName + '-fixed');
        classAttributeInput.value = states.attributePoints.class[curAttributeName]
    })
}

function updateUIAttributePointsEditable() {
    attributesJSON.forEach(curAttribute => {
        const curAttributeName = curAttribute.label;

        const editableAttributeInput = document.getElementById(curAttributeName);
        editableAttributeInput.value = states.attributePoints.level[curAttributeName];
    })
}

function updateUIAttributePointsFinal() {
    attributesJSON.forEach(curAttribute => {
        const curAttributeName = curAttribute.label;

        const finalAttributeInput = document.getElementById(curAttributeName + '-total');
        finalAttributeInput.value = states.attributePoints.final[curAttributeName];
    })
}

Make query with “where” filter in Firestore

I want to filter and get specific items based on the categoryID, where i use the “where” method and the “==” operator.

I have this Firestore collection called “task”, where the documents are divided by userID and each document for a user contains an array of different tasks. The structur is seen here:
Enter image description here

This is how i add the array tasks for an user in the task collection:

const addToFirebase = async() => {
    if(dataFetch) {
      await setDoc(doc(db, "task", `${firebase.auth().currentUser.uid}`), {
        tasks: tasks
      }, {merge: true});
    }
  }

And this is how i have tried to make my query that is not working:

 const getFilteredTasks = async() => {
    const collectionRef = collection(db, "task", `${firebase.auth().currentUser.uid}`, "tasks");
    const q = query(collectionRef, where("categoryID", "==", item.id));

    console.log('outside snapshot')
    console.log(item.id)

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      console.log(doc.data());
      console.log('inside snapshot')
    });
  }

When the above function is called, it logs the “outside snapshot” and the correct item.id, which is the categoryID for each task, but it does not log the doc.data() and the “inside snapshot”.

Form required section in react

there is required section in my form also I want to send successfully text after click of submit button. But problem is here when I click submit button, it shows successfully text no matter form is correct or not. Can you help me about that ? I am beginner 🙂

My react code here

import React, { Component } from "react";

export default class Form extends Component {
  state = {
    name: "",
    surname: "",
    phone: "",
    email: "",
    comments: "",
    // isValid: true,
    succesfully: ""
  };

  // preventSending = async (e) => {
  //   await this.setState({ [e.target.name]: e.target.value });
  //   if (
  //     this.state.name === "" ||
  //     this.state.surname === "" ||
  //     this.state.phone === "" ||
  //     this.state.email === "" ||
  //     this.state.comments === ""
  //   ) {
  //     this.setState({ isValid: true });
  //   } else {
  //     this.setState({ isValid: false });
  //   }
  // };

  handleSubmit = (e) => {
    this.setState({
      succesfully: `${this.state.name} you have sent successfully `
    });
  };

  render() {
    return (
      <div className="">
        <form>
          <label htmlFor="name">
            Name :
            <input
              onChange={this.preventSending}
              id="name"
              name="name"
              type="text"
              required
            />
          </label>
          <br />
          <label htmlFor="surname">
            Surname :
            <input
              onChange={this.preventSending}
              id="surname"
              name="surname"
              type="text"
              required
            />
          </label>
          <br />
          <label htmlFor="phone">
            Phone :
            <input
              onChange={this.preventSending}
              id="phone"
              name="phone"
              type="tel"
              required
            />
          </label>
          <br />
          <label htmlFor="email">
            Email :
            <input
              onChange={this.preventSending}
              id="email"
              name="email"
              type="email"
              required
            />
          </label>
          <br />
          <label htmlFor="textArea">
            Comments :
            <textarea
              onChange={this.preventSending}
              id="textarea"
              name="comments"
              required
            />
          </label>
          <br />
          <button
            type="submit"
            // disabled={this.state.isValid}
            onClick={this.handleSubmit}
          >
            Send details{" "}
          </button>
        </form>

        <p>{this.state.succesfully}</p>
      </div>
    );
  }
}

It says I have to add more details but I explained everything clear.

How make React admin’s behave as a stack on item addition (add item on top)?

I have an item with a nested list of items. I can edit these nested items individually using a <SimpleFormIterator> mixed with a <FormDataConsumer>. The issue is that when i insert a new item in the list, it becomes the last item. I would like it to be the first, and shift every other item down a slot.

Maybe something like using a custom with an addOnTop callback could help? But I don’t see a way to make it work without rewriting the whole component from scratch.

<SimpleFormIterator
     addButton={<ListAddButton onClick={addOnTop??} />}
     removeButton={<ListRemoveButton />}
>
...
</SimpleFormIterator>

React function uses outdated state

I am using react-query to fetch external data, based on the current state here is how the code looks like

const Home = () => {
  const queryClient = useQueryClient();
  const [group, setGroup] = useState(1);

  const query = useQuery('/query', async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });

  useEffect(() => {
    queryClient.invalidateQueries('/query');
  }, [group, queryClient]);

  return (
    <div>
      <button onClick={() => setGroup(1)}>First group</button>
      <button onClick={() => setGroup(2)}>Second group</button>
    </div>
  );
};

There are 2 buttons that changes the state (group), and when the state changes (useEffect) I invalidate old queries to send new queries but the problem is that the callback has only the initial state and not the updated state and when it get executed it prints out the initial state

Argument of type ‘Blob’ is not assignable to parameter of type ‘string | Blob’

Just got an error:

Argument of type 'Blob' is not assignable to parameter of type 'string | Blob'.
  Type 'import("buffer").Blob' is not assignable to type 'Blob'.
    The types returned by 'stream()' are incompatible between these types.
      Type '{}' is missing the following properties from type 'ReadableStream<any>': locked, cancel, getReader, pipeThrough, and 2 more.

And can’t understand what’s going on. Tried to restart vscode but didn’t help. Blob is not assignable to param of type Blob. ?! So Blob returned by stream is not the same with usual Blob?

This is my code

    const audioBuffer = fs.readFileSync(`./uploads/audio/${filePath}`)
    const audioBlob = new Blob([audioBuffer])
    const formData = new FormData()
    formData.append('file', audioBlob)

Error is showing when i’m trying to append file to formdata

Make a MySQL query reusable with double ?? for tables and ? for selectors with NodeJS and JavaScript

Hi. I am looking to create a reusable query with MySQL and NodeJS

The first step I took after the DB connection was to create a data access object and interact with the DB while using promises. To stay relative secure, I am using placeholders:

  • ” ? ” for rows and values and double ” ?? ” for tables.

I want to create functions to be reused. So if I am creating one function for insert, I need to use same function to insert records in different tables while using parameters.

  1. The Data access layer looks like this: Here I am using parameters that will go to each function and replace the placeholders from the sql statements.

           /* 
               Insert user accepts three parameters. Statement from mysql, table marked with ?? in the statement and the 
               payload object that have to match the database columns 
           */
           insertRecord: (sqlStatement, table, payload) => {
               return new Promise((resolve, reject) => {
                   db.query(sqlStatement, [table, payload], (error, response) => {
                   if (error) return reject(error);
                   return resolve(response);
               });
             });
           },
    
       /* 
           This function accepts four parametters. The first parameter is the statement. Second parameter is the table selector 
           marked with ?? in the statement.
           The selector is the row, and the value specified
       */
       selectSimpleStatement: (sqlStatement, table, row, value) => {
           return new Promise((resolve, reject) => {
               db.query(sqlStatement, [table, row, value], (error, response) => {
               if (error) return reject(error);
               else return resolve(response);
           });
         });
       }
    }
    
    
    
    
  2. The second implementation was to create all the MySQL queries separately because I wanted to keep it Clean

    module.exports = {
    insertStatement: ‘INSERT INTO ?? SET ?’,
    sqlSimpleSelect: ‘SELECT * FROM ?? WHERE ? = ?’
    }

  3. Using the first sql statement was easy. I worked to insert in all the tables with the same function. But the select is a pain. With postman I am getting empty arrays even if the values are correct…

const { sqlSimpleSelect } = require('../../database/statements.js');
const bcrypt = require('bcrypt');



exports.add = async (req, res, next) => {
    const {username, password} = req.body;

try {
    // Select from users where username = username variable
    const user = await selectSimpleStatement(sqlSimpleSelect, 'users', 'username', username);
    res.send(user);
} 
catch (error) {
    res.send(error)
    }
}```


I am getting empty array. Can please help me? 
Thanks, Daniel

Detect scrolling to a video and then playing it

I have a simple web page with a video inside, I would like that when you scroll to the div containing the video the scroll would be deactivated and replaced with the video controls (if I scroll down the video plays on 1 frame per scroll, if I scroll up the video reverse). Obviously if the video ends the scroll must reactivate and continue to the bottom of the page (same thing if I send the video back to the beginning).
This is the video in question:

    <div id="bound-one" class="scroll-bound">
        <div class="content">
            <video id="video1" width="100%" muted preload >
                <source src="video.mp4">
      </video>
        </div>
    </div>
</div> ```

Trigger a JavaScript function on a WebView in Flutter

I have a webpage that I load on a WebViw in flutter and that webpage has a javascript function that I want to run with a parameter from flutter.

I wrote this uderneath, but I cannot use the Webview Controller functions because it expects a FutureOr<WebViewController>. Also, does the rest of my code make sense? As in, will it run whichever js function I pass it in runJavascriptReturningResult(' ')?

  final String url;
  final String title;

  WebViewPageState(this.url, this.title);

  final Completer<WebViewController> _controller = Completer<WebViewController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(this.title),
        ),
        body: Column(children: [
          Expanded(
              child: WebView(
                  initialUrl: this.url,
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webviewcontroller) {
                    _controller.complete(webviewcontroller.runJavascript('alert("Hello, World!")'));
                  },
              ))
        ]));
  }
} ```