React Router 6: Retrieving a query string once per page reload

I’m having a need to implement the following behavior in my React application:

  • Whenever a page is loaded (either opened in a browser or refreshed), certain components must retrieve parameters from a query string.
  • React application should be able to modify the query string without reloading a page.
  • Whenever a component retrieving the query string on initial loading / refreshing of a page vanishes but appears again (for example, whenever a tab is switched), it is considered its first render, but it should not provoke additional retrieving of the query string’s parameters.

I have tried:

  • Using useEffect with empty array on target component(-s). Didn’t work well because it was triggering every time I changed a tab (the disappearance of any component is considered its unmount, and its appearance after that is considered a mount, leading to the satisfied condition for a useEffect running on initial render).
  • Using Context API to store the query string in index.js file of an application, and retrieving the context of that query string by target component(-s). Didn’t work due to the same reason: useContext did re-run on re-rendering.

Is there a pattern people use in React with React-Router v6 to achieve this?

Keep content center screen but have it change on scroll

I have an idea I want to try to implement but I don’t know the best way to go about it.

I want to center content on the screen and instead of have it scroll off the screen and new content scroll in, I would like to keep it center screen it fade transform into the next content.

So when the user scrolls to “Content 1” it locks that center screen and then when the user scrolls it fades into “Content 2” and then when the user is scrolling past “Content 3” it goes back to normal scrolling behavior.

How can I do this with vanilla JS and CSS? I need this to work on mobile (touch) and desktop (wheel).

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<p>Normal scrolling content</p>

<div class="min-h-screen flex justify-center content-center items-center">
<h2>Content 1</h2>
</div>

<div class="min-h-screen flex justify-center content-center items-center">
<h2>Content 2</h2>
</div>

<div class="min-h-screen flex justify-center content-center items-center">
<h2>Content 3</h2>
</div>

<p>Rest of the normal scrolling content</p>

How to expand a shortened Google maps url in javascript – react native

I am building react native app and trying to get the shared object from “share this place” in Google maps.

I used this in AndroidManifest.xml:

   <intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
    <data android:mimeType="image/*" />
  </intent-filter>

and react-native-share-menu library

  const handleShare = useCallback(async (item) => {
    console.log(item);
  }, []);


  useEffect(() => {
    const listener = ShareMenu.addNewShareListener(handleShare);

    return () => {
      listener.remove();
    };
  }, []);

This is what I got from console.log:

Object {
  "data": "Primera Compound
https://maps.app.goo.gl/CzntauZsuVuDVjrZ9",
  "mimeType": "text/plain",
}

What I need is to get the extended Url from this shortened Url https://maps.app.goo.gl/CzntauZsuVuDVjrZ9 which will be something like this:
https://www.google.com/maps/place/Primera+Compound/@30.038217,31.3669955,17.25z/data=!4m5!3m4!1s0x14583c3319872c3f:0x19624433cfed553d!8m2!3d30.0383908!4d31.368642

I need to know if there is a way to do this without API?
I want to access the lat and long of this shared object.

ObjectSpaceNormalMap not working with MeshNormalMaterial

I’m trying to get MeshNormalMaterial to stay aligned with the object rather than the camera. As far as I know, setting .normalMapType = THREE.ObjectSpaceNormalMap is supposed to do this. However it isn’t.

Is there something I’m missing or an alternative in order to make this work?

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
camera.position.applyAxisAngle(new THREE.Vector3(1, 0, 0), 0.3);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}, false);

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshNormalMaterial();
material.normalMapType = THREE.ObjectSpaceNormalMap;
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update();

function animate() {
    requestAnimationFrame(animate);

    //cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    controls.update();
    
    renderer.render(scene, camera);
};

animate();
body { margin: 0; overflow: hidden; background: black; }
<script src="https://unpkg.com/[email protected]/build/three.js"></script>
<script src="https://unpkg.com/[email protected]/examples/js/controls/OrbitControls.js"></script>

Gets firebase emulator updates on a another project

i am running emulator on app a with the following command :

firebase emulators:start --import=./emulator-data --only=auth,firestore,functions,storage,pubsub",

from APP B im just connecting to the emu by adding the
FIRESTORE_EMULATOR_HOST=8080

the issue is when I am going directly to the emu i will get only the based data that saved to the file

I wont get the new collection or new entry if i will try to add or even if i will restart the second app .
i will always get the original data and only the original data

how can it be fixed ?

How to get value of the HTML element? [duplicate]

I have a question, how can i get value of the element using javaScript with Jquery? I have tried this and error sad .val() is not a function and i could not find any solution. Everithink i found told me it is not a function. Thanks for reply.

const btn = $('.btn');
let example = $('#example');
let result = $('#result');
var test = btn.value;


btn.on('click', function(){
    console.log($(this).val());
})
.btn{
    border-radius: 5px;
    margin-top: 3vh;
    float: left;
    margin-left: 4%;
    width: 20%;
    height: 12vh;
    background: red;
    line-height:12vh;
    text-align: center;
    font-size:300%;
    font-weight: bold;
}
            <div class="btn" val="1">1</div>

**

**

Cannot add fog effect to the scene with skybox in the scene

I was trying to create the fog effect in the scene and I also have the skybox created within the scene, I expected the fog effect to be applied to the skybox but it doesn’t happen so.
Is it because we cant apply fog effect on geometries mapped with textures? If i console log scene out fog is inherited in scene. But still the screen is black black screen
code

    import * as THREE from 'https://unpkg.com/[email protected]/build/three.module.js';
import {OrbitControls} from 'https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls.js';
    
    var scene , camera , renderer;
    function init(){
    
     scene = new THREE.Scene()
     {
         let color = 0x000000;
         let density = 0.1;
         scene.fog = new THREE.FogExp2(color,density);
     }
    
     camera = new THREE.PerspectiveCamera(
        80,
        window.innerWidth/window.innerHeight,
        45,
        30000
    );
    camera.position.set(-900,-200,-900);
    scene.add(camera);
    
     renderer = new THREE.WebGLRenderer(
         {
             antialias : true
         }
     );
    renderer.setSize(window.innerWidth,window.innerHeight);
    renderer.setPixelRatio(devicePixelRatio);
    renderer.setClearColor(0x000000);
    document.body.appendChild(renderer.domElement);
    
    let controls = new OrbitControls(camera,renderer.domElement);
    controls.addEventListener('change', renderer);
    controls.minDistance = 500;
    controls.maxDistance = 1500;
    
    
    let materialarray = [];
    let texture_ft = new THREE.TextureLoader().load('tropic_ft.jpg');
    let texture_bk = new THREE.TextureLoader().load('tropic_bk.jpg');
    let texture_up = new THREE.TextureLoader().load('tropic_up.jpg');
    let texture_dn = new THREE.TextureLoader().load('tropic_dn.jpg');
    let texture_rt = new THREE.TextureLoader().load('tropic_rt.jpg');
    let texture_lf = new THREE.TextureLoader().load('tropic_lf.jpg');
    
    materialarray.push(new THREE.MeshBasicMaterial({map : texture_ft}));
    materialarray.push(new THREE.MeshBasicMaterial({map : texture_bk}));
    materialarray.push(new THREE.MeshBasicMaterial({map : texture_up}));
    materialarray.push(new THREE.MeshBasicMaterial({map : texture_dn}));
    materialarray.push(new THREE.MeshBasicMaterial({map : texture_rt}));
    materialarray.push(new THREE.MeshBasicMaterial({map : texture_lf}));
    
    for(let i = 0; i < 6; i++)
    {
        materialarray[i].side = THREE.BackSide;
    }
    
    let skyboxgeo = new THREE.BoxGeometry(1000,1000,1000);
    let skybox = new THREE.Mesh(skyboxgeo,materialarray);
    scene.add(skybox);
    
    animate();
    }
    
    function animate(){
        renderer.setSize(window.innerWidth,window.innerHeight);
        requestAnimationFrame(animate);
    
    
        renderer.render(scene , camera);
    }
    
    init();

POST request issues to Twitter API

I have been using NextJS, Twitter-lite to build an application using the twitter app, I basically am trying to implement the functionality in which users can post a tweet from the app to their twitter accounts. I have also used Next-Auth for implementing oAuth for twitter.

Here is my code for the api/twitter/post.js

import Twitter from "twitter-lite";
import { getSession } from "next-auth/react";
import { getToken } from "next-auth/jwt";
export default async (req, res) => {
  const session = await getSession({ req });
  const token = await getToken({
    req,
    secret: process.env.NEXTAUTH_SECRET,
  });

  const client = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: token.twitter.accessToken,
    access_token_secret: token.twitter.refreshToken,
  });

  const response = await client.getBearerToken();
  const app = new Twitter({
    bearer_token: response.access_token,
  });

  const tweet = await app.post("statuses/update", {
    status: req.body,
  });

  return res.status(200).json({ status: "ok", data: req.body });
};

However, This returns an error –

Error: {“_headers”:{},”errors”:[{“code”:220,”message”:”Your credentials do not allow access to this resource.”}]}

Since I also have the bearer_tokens, I shouldn’t be restricted from doing this, I’m not sure if I’m doing something wrong since Twitter API is just so complicated to comprehend

how to resolve ctx.draw is not a function error

I am currently making a Flappy Bird game on HTML canvas, and I encountered an error which says

game.js:85 Uncaught TypeError: ctx.draw is not a function
    at PipeSpawner.draw (game.js:85:17)
    at gameLoop (game.js:109:17)

It is really confusing for me, since all the other ctx.draw functions i have in my other classes all work just fine.
Here is my game.js file, where all my code is stored



let canvas = document.getElementsByTagName("canvas")[0]
let ctx = canvas.getContext('2d')

const WIDTH = 500
const HEIGHT = 666
let dead = false;

class Bird {
    constructor() {
        this.birdImage= document.getElementById("bird")
        this.position = {x: WIDTH/2 - this.birdImage.width/2, y:HEIGHT/2 - this.birdImage.height/2}
        this.gravity = 1
        this.jumpForce = 20
        this.ground = ground
    }
    fall() {
        this.position.y += this.gravity
    }
    jump() {
        this.position.y -= this.jumpForce
    }
    update() {
  
        this.draw(ctx)
        this.fall()
        this.checkCollisionWithGround()

        if (dead) {
            this.gravity = 0
        }
    }  
    draw(ctx) {
        ctx.drawImage(this.birdImage,this.position.x,this.position.y)
    }

    checkCollisionWithGround() {
        let bottomOfBird = this.position.y + this.birdImage.height
        let topOfGround = HEIGHT - this.ground.ground.height;

        if (bottomOfBird >= topOfGround) {
            dead = true;
        }
    }

}

class Ground {
    constructor() {
        this.ground = document.getElementById("ground")
        this.ppsition= {}

    }

    draw(ctx) {
        ctx.drawImage(this.ground,0,HEIGHT - this.ground.height)
        ctx.drawImage(this.ground,this.ground.width,HEIGHT- this.ground.height)

    }

    
}

class PipeSpawner {
    constructor() {
        this.pipeNorth = document.getElementById("preview-pipenorth")
        this.pipeSouth = document.getElementById("preview-pipesouth")
        this.minY = 100
        this.maxY = 300
        this.gap = 50;
        this.spawnX = 50;
    }

    getRandomYValue() {
        return (Math.random() * this.minY) + (this.maxY - this.minY);
    }

    addPipe() {
        let randomYVal = (Math.random() * this.minY) + (this.maxY - this.minY)
        pipes.push([{x:this.spawnX, y: randomYVal}, {x: this.spawnX, y: randomYVal + this.gap}])
    }

    draw() {
        for (let i=0 ; i<pipes.length; i++) {
            ctx.draw(this.pipeNorth,pipes[i][0].x, pipes[i][0].y)

        }
    }


}
let ground = new Ground()
let bird = new Bird()
let pipeSpawner = new PipeSpawner()
let pipes = [[{x:pipeSpawner.spawnX, y:200}, {x:pipeSpawner.spawnX, y:200+ pipeSpawner.gap}]]

function checkKeyEvent(event) {
    switch (event.keyCode) {
        case 32: 
            bird.jump()
    }
}
window.setInterval(pipeSpawner.addPipe,5000)
function gameLoop() {

    ctx.clearRect(0,0,WIDTH,HEIGHT)
    window.addEventListener('keydown',checkKeyEvent)
    ground.draw(ctx)
    pipeSpawner.draw()

    bird.update()
    requestAnimationFrame(gameLoop)
}

requestAnimationFrame(gameLoop)


Can anyone help me understand what exactly is going on in my application, and how to resolve it? Help is greatly appreciated.

Why is React/Firebase rendering my Cloudify images as plain text instead of an image?

In my React app I have no problem uploading images to Cloudify and then grabbing the url as a variable as so:

const formData = new FormData();
formData.append("file", imageSelected);
formData.append("upload_preset", "My_Preset");

axios.post("https://api.cloudinary.com/v1_1/my-profile/image/upload", formData).then((response) => {
  console.log(response);
  setImageUrl(response.data.url);
});

But when I try to display that as an image in JSX after sending the info to Firebase (dbmessage.text being the url):

if (dbmessage.type === 'media' && name === dbmessage.name) {
        return (
          <div>
            <div className="MyRow">s
              <div className="MyMessage">
                <img className="img-message" src={dbmessage.text}/>
              </div>
          </div>
          <div className="my-name">
            {name}
          </div>
        </div>
        )
      }

I am greeted with my message coming back as the url as plain text. Ex: http://res.cloudinary.com/hidden/image/upload/hidden/hidden/x3bvt1rq7tiqr0hcumo7.png

I can paste this url into my browser and I’m redirected to the image so the url is fine, but in Inspect the tag is nowhere to be found and is instead the url as #text. I have no idea why the url is showing up like this or why the img tag failes to render at all.

On top of this I’ve tried using <Image className="img-message" cloudName="hidden" publicID={imageUrl}/> from cloudify with no luck however both with <Image/> and <img/> tags when not being used with to display a Firebase message, they render out the images just fine.

Ex: <Image className="img-message" cloudName="hidden" publicID={imageUrl}/> used alone grabs the image and shows it on the screen without any problems, it’s only an issue once I start trying to upload and grab the url with Firebase. Any ideas?

AWS-Amplify, How do I redirect to another URL after sign-in in angular?

I’m using the latest AWS-Amplify’s authentication component. It can logged in successfully but after login I need to sent the route to another url which I can’t able to achieve, it keeping the same url after logged in. BUT I need to set a custom url where it automatically redirect if a user login successfully.

Note : I’m not using aws-amplify-angular package I’m using these packages,

 "@aws-amplify/ui-angular": "^2.4.4", 
 "aws-amplify": "^4.3.21",

Also I checked this import {AuthenticatorService} from '@aws-amplify/ui-angular'; service but here I didn’t find any response with observable type, I think that’s why I don’t get any event or something instantly after user login successfully. I need to route imminently after a successful login. So I need an event so that I can do that .

My main.ts :

import { Amplify } from 'aws-amplify'
import awsmobile from './aws-exports'
Amplify.configure(awsmobile)

auth.component.html : [ there is no code in ts ]

<amplify-authenticator [signUpAttributes]="['email']"></amplify-authenticator>

& the routes setup like this,

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'auth',
    component: AuthComponent
  },
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  }
];

I didn’t get any good solution with using this packages. Please help with this issue or am I missed something in my configuration .

how to add drop down list in material-UI Search component in navbar, for search results

I was using material ui search bar into navbar from app-bar-with-search-field official documnets from MUI in my react app. but this article it does not mention how to add dropdown list on selecting search input field.

I was tried many ways including Menu, List components from MUI for implement drop menu but didn’t work for me. please help me to figure it out how i can add dropdown list of width of serach bar for showing a search results.
codesendbox link

code in my App.js

import "./styles.css";
import * as React from "react";
import { styled, alpha } from "@mui/material/styles";
import Box from "@material-ui/core/Box";
import InputBase from "@mui/material/InputBase";
import SearchIcon from "@mui/icons-material/Search";

const Search = styled("div")(({ theme }) => ({
  position: "relative",
  borderRadius: theme.shape.borderRadius,
  backgroundColor: alpha(theme.palette.common.black, 0.15),
  "&:hover": {
    backgroundColor: alpha(theme.palette.common.black, 0.25)
  },
  marginTop: "5px",
  marginLeft: 0,
  width: "100%",
  [theme.breakpoints.up("sm")]: {
    marginLeft: theme.spacing(1),
    width: "auto"
  }
}));

const SearchIconWrapper = styled("div")(({ theme }) => ({
  padding: theme.spacing(0, 2),
  height: "100%",
  position: "absolute",
  pointerEvents: "none",
  display: "flex",
  alignItems: "center",
  justifyContent: "center"
}));
const StyledInputBase = styled(InputBase)(({ theme }) => ({
  color: "red",
  "& .MuiInputBase-input": {
    padding: theme.spacing(1, 1, 1, 0),
    // vertical padding + font size from searchIcon
    paddingLeft: `calc(1em + ${theme.spacing(4)})`,
    transition: theme.transitions.create("width"),
    width: "100%",
    [theme.breakpoints.up("sm")]: {
      width: "12ch",
      "&:focus": {
        width: "20ch"
      }
    },
    [theme.breakpoints.down("sm")]: {
      width: "0ch",
      "&:focus": {
        width: "12ch"
      }
    }
  }
}));

export default function App() {
  return (
    <div className="App">
      <div>
        <nav
          id="navbar"
          className=" pt-0 pb-0 ps-3 container-row navbar-dark navbar navbar-expand-lg nav-div fixed-top"
        >
          <div className="container">
            <div className="navbar-brand">
              <h1 className="logo-text mt-1 text-dark">project logo</h1>
            </div>
            <div className="nav-list">
              <ul className="nav navbar-nav ms-auto mb-2 mb-lg-0">
                <React.Fragment>
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      textAlign: "center"
                    }}
                  >
                    <Search>
                      <SearchIconWrapper>
                        <SearchIcon />
                      </SearchIconWrapper>
                      <StyledInputBase
                        placeholder="Search Organization ..."
                        inputProps={{ "aria-label": "search" }}
                      />
                    </Search>
                  </Box>
                </React.Fragment>
              </ul>
            </div>
          </div>
        </nav>
      </div>
    </div>
  );
}


thank you.