ValidationError when trying to create an object in mongodb

When trying to send request via axios to backend(mongodb) , throws validation error. and this only happens while trying to create product via front-end. i tried creating product via Postman and it works fine.
Addproductpage


import { React, useEffect, useState } from "react";
import CustomInput from "../components/CustomInput";
import ReactQuill from "react-quill";
import { useNavigate } from "react-router-dom";
import "react-quill/dist/quill.snow.css";
import { toast } from "react-toastify";
import * as yup from "yup";
import { useFormik } from "formik";
import { useDispatch, useSelector } from "react-redux";
import { getBrands } from "../features/brand/brandSlice";
import { getPCategory } from "../features/pCategory/pCategorySlice";
import { getColors } from "../features/color/colorSlice";
import { Select } from "antd";
import Dropzone from "react-dropzone";
import { delImg, uploadImg } from "../features/upload/uploadSlice";
import { createProducts, resetState } from "../features/product/productSlice";
let schema = yup.object().shape({
  title: yup.string().required("Title is Required"),
  description: yup.string().required("Description is Required"),
  price: yup.number().required("Price is Required"),
  brand: yup.string().required("Brand is Required"),
  category: yup.string().required("Category is Required"),
  tags: yup.string().required("Tag is Required"),
  color: yup
    .array()
    .min(1, "Pick at least one color")
    .required("Color is Required"),
  quantity: yup.number().required("Quantity is Required"),
});

const Addproduct = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [color, setColor] = useState([]);
  const [images, setImages] = useState([]);
  console.log(color);
  useEffect(() => {
    dispatch(getBrands());
    dispatch(getPCategory());
    dispatch(getColors());
  }, []);

  const brandState = useSelector((state) => state.brands.brands);
  const catState = useSelector((state) => state.productCategories.productCategory);
  const colorState = useSelector((state) => state.colors.colors);
  const imgState = useSelector((state) => state.upload.images);
  const newProduct = useSelector((state) => state.products.products);
  const { isSuccess, isError, isLoading, createdProduct } = newProduct;
  useEffect(() => {
    if (isSuccess && createdProduct) {
      toast.success("Product Added Successfullly!");
    }
    if (isError) {
      toast.error("Something Went Wrong!");
    }
  }, [isSuccess, isError, isLoading]);
  const coloropt = [];
  colorState.forEach((i) => {
    coloropt.push({
      label: i.title,
      value: i._id,
    });
  });
  const img = [];
  imgState.forEach((i) => {
    img.push({
      public_id: i.public_id,
      url: i.url,
    });
  });

  useEffect(() => {
    formik.values.color = color ? color : " ";
    formik.values.images = img;
  }, [color, img]);
  const formik = useFormik({
    initialValues: {
      title:"",
      description:"",
      price:"",
      brand:"",
      category:"",
      tags:"",
      color:"",
      quantity:"",
      images:"",
    },
    validationSchema: schema,
    onSubmit: (values) => {
      alert(JSON.stringify(values));
     dispatch(createProducts(values));
      formik.resetForm();
      setColor(null);
      setTimeout(() => {
         dispatch(resetState());
       }, 3000);
    },
  });
  const handleColors = (e) => {
    setColor(e);
    console.log(color);
  };
  return (
    <div>
      <h3 className="mb-4 title">Add Product</h3>
      <div>
        <form
          onSubmit={formik.handleSubmit}
          className="d-flex gap-3 flex-column"
        >
          <CustomInput
            type="text"
            label="Enter Product Title"
            name="title"
            onCh={formik.handleChange("title")}
            onBlr={formik.handleBlur("title")}
            val={formik.values.title}
          />
          <div className="error">
            {formik.touched.title && formik.errors.title}
          </div>
          <div className="">
            <ReactQuill
              theme="snow"
              name="description"
              onChange={formik.handleChange("description")}
              value={formik.values.description}
            />
          </div>
          <div className="error">
            {formik.touched.description && formik.errors.description}
          </div>
          <CustomInput
            type="number"
            label="Enter Product Price"
            name="price"
            onCh={formik.handleChange("price")}
            onBlr={formik.handleBlur("price")}
            val={formik.values.price}
          />
          <div className="error">
            {formik.touched.price && formik.errors.price}
          </div>
          <select
            name="brand"
            onChange={formik.handleChange("brand")}
            onBlur={formik.handleBlur("brand")}
            value={formik.values.brand}
            className="form-control py-3 mb-3"
            id=""
          >
            <option value="">Select Brand</option>
            {brandState.map((i, j) => {
              return (
                <option key={j} value={i.title}>
                  {i.title}
                </option>
              );
            })}
          </select>
          <div className="error">
            {formik.touched.brand && formik.errors.brand}
          </div>
          <select
            name="category"
            onChange={formik.handleChange("category")}
            onBlur={formik.handleBlur("category")}
            value={formik.values.category}
            className="form-control py-3 mb-3"
            id=""
          >
            <option value="">Select Category</option>
            {catState.map((i, j) => {
              return (
                <option key={j} value={i.title}>
                  {i.title}
                </option>
              );
            })}
          </select>
          <div className="error">
            {formik.touched.category && formik.errors.category}
          </div>
          <select
            name="tags"
            onChange={formik.handleChange("tags")}
            onBlur={formik.handleBlur("tags")}
            value={formik.values.tags}
            className="form-control py-3 mb-3"
            id=""
          >
            <option value="" disabled>
              Select Category
            </option>
            <option value="featured">Featured</option>
            <option value="popular">Popular</option>
            <option value="special">Special</option>
          </select>
          <div className="error">
            {formik.touched.tags && formik.errors.tags}
          </div>

          <Select
            mode="multiple"
            allowClear
            className="w-100"
            placeholder="Select colors"
            defaultValue={color}
            onChange={(i) => handleColors(i)}
            options={coloropt}
          />
          <div className="error">
            {formik.touched.color && formik.errors.color}
          </div>
          <CustomInput
            type="number"
            label="Enter Product Quantity"
            name="quantity"
            onCh={formik.handleChange("quantity")}
            onBlr={formik.handleBlur("quantity")}
            val={formik.values.quantity}
          />
          <div className="error">
            {formik.touched.quantity && formik.errors.quantity}
          </div>
          <div className="bg-white border-1 p-5 text-center">
            <Dropzone
              onDrop={(acceptedFiles) => dispatch(uploadImg(acceptedFiles))}
            >
              {({ getRootProps, getInputProps }) => (
                <section>
                  <div {...getRootProps()}>
                    <input {...getInputProps()} />
                    <p>
                      Drag 'n' drop some files here, or click to select files
                    </p>
                  </div>
                </section>
              )}
            </Dropzone>
          </div>
          <div className="showimages d-flex flex-wrap gap-3">
            {imgState?.map((i, j) => {
              return (
                <div className=" position-relative" key={j}>
                  <button
                    type="button"
                    onClick={() => dispatch(delImg(i.public_id))}
                    className="btn-close position-absolute"
                    style={{ top: "10px", right: "10px" }}
                  ></button>
                  <img src={i.url} alt="" width={200} height={200} />
                </div>
              );
            })}
          </div>
          <button
            className="btn btn-success border-0 rounded-3 my-5"
            type="submit"
          >
            Add Product
          </button>
        </form>
      </div>
    </div>
  );
};

export default Addproduct;


productService

import axios from "axios";
import config from "../../app/utils/axiosconfig";


const getProducts = async ()=>

{
    const response = await axios.get('http://localhost:5000/api/products/allproduct');
    
    return response.data;
}
const createProduct = async(product)=>{
    console.log(product);
    const response = await axios.post('http://localhost:5000/api/products/',product,config);
    return response.data;
}

const productService ={
    getProducts,
    createProduct,
}

export default productService;

productslice

import { createSlice,createAsyncThunk, createAction } from "@reduxjs/toolkit";

import productService from "./productService";



const initialState ={
    products: [],
    isError: false,
    isLoading:false,
    isSuccess: false,
    message: "",
}
export const getproducts = createAsyncThunk('product/get-products',async(thunkApi)=>{
    try {
        return await productService.getProducts();
    } catch (error) {
        return thunkApi.rejectWithValue(error);
    }
 });
 export const createProducts = createAsyncThunk('Add/product',async(thunkApi,productData)=>{
    try {
        return await productService.createProduct(productData);
    } catch (error) {
        return thunkApi.rejectWithValue(error)
    }
 })

 export const resetState = createAction("Reset_all");

export const productSlice = createSlice({
    name: "products",
    initialState,
    reducers:{},
    extraReducers:(builder)=>{
        builder.addCase(getproducts.pending,
        (state)=>{
            state.isLoading = true;
        }).addCase(getproducts.fulfilled,
            (state,action)=>{
                state.isLoading = false;
                state.isSuccess = true;
                state.products = action.payload;
            }).addCase(getproducts.rejected,
                (state,action)=>{
                    state.isLoading = false;
                    state.isError = true;
                    state.isSuccess = false;
                    state.message= action.error;
                    
                }).addCase(createProducts.pending,(state)=>{
                    state.isLoading=true;
                }).addCase(createProducts.fulfilled,(state,action)=>{
                    state.isError=false;
                    state.isLoading=false;
                    state.isSuccess = true;
                    state.createdProduct = action.payload;
                }).addCase(createProducts.rejected,(state,action)=>{
                    state.isError=true;
                    state.isLoading=false;
                    state.isSuccess = false;
                    state.message = action.error;}).addCase(resetState,()=> initialState);
    },
})
export default productSlice.reducer;

the values from front end[the error]success in postman(https://i.stack.imgur.com/XCmuq.png)

I am trying to create a product,

product model

const mongoose = require("mongoose"); // Erase if already required

// Declare the Schema of the Mongo model
var productSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
      trim: true,
    },
    slug: {
      type: String,
      required: true,
      unique: true,
      lowercase: true,
    },
    description: {
      type: String,
      required: true,
    },
    price: {
      type: Number,
      required: true,
    },
    category: {
      type: String,
      required: true,
    },
    brand: {
      type: String,
      required: true,
    },
    quantity: {
      type: Number,
      required: true,
    },
    sold: {
      type: Number,
      default: 0,
    },
    images: [
      {
        public_id: String,
        url: String,
      },
    ],
    color: [],
    tags: String,
    ratings: [
      {
        star: Number,
        comment: String,
        postedby: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
      },
    ],
    totalrating: {
      type: String,
      default: 0,
    },
  },
  { timestamps: true }
);

//Export the model
module.exports = mongoose.model("Product", productSchema);

product controller

const createProduct = asyncHandler(async (req, res) => {
  try {
    if (req.body.title) {
      req.body.slug = slugify(req.body.title);
    }
    const newProduct = await Product.create(req.body);
    res.json(newProduct);
  } catch (error) {
    throw new Error(error);
  }
});

btw i’m new to web development,apologies for poor representation of the problem. thanks

question about making an element visible on click

im trying to make a portfolio that gets my works from a db, I’m using PHP for that.
this is the loop to display all my works:

<?php
        while($row = mysqli_fetch_assoc($result)) {
          echo "<div class='work__box'>";
          echo  "<div class='work__text'>";
          echo    "<h3 class='title'>" . $row["name"] . "</h3>";
          echo      "<div class='more_details'>";
          echo        "<p>" . $row["description"] . "</p>";
          echo        "<div class='work__links'>";
          echo        "<a href='" . $row["project_url"] . "' target='_blank' class='link__text'>";
          echo        "Visit Site <span>&rarr;</span>";
          echo        "</a>";
          echo        "<a href='" . $row["github_url"] . "' title='View Source Code' target='_blank'>";
          echo        "<img src='./images/github.svg' class='work__code' alt='GitHub'>";
          echo        "</a>";
          echo      "</div>";
          echo    "</div>";
          echo  "</div>";
          echo  "<div class='work__image-box'>";
          echo    "<img src='." . $row["image"] . "' class='work__image' alt='Project_image' />";
          echo  "</div>";
          echo "</div>";
        }
      ?>

the problem I can’t seems to solve is making the more_details hidden and when the title is being clicked it will appear below it. I’ve tried using JS and toggle, tried onclick event but seems like nothing make it appear.
will appreciate any answer and if something is missing ill gladly upload.
thanks in advance!

Expanding and closing a list of files for my website

I have created a file sharing website with PHP. The files are many and I want to narrow it and when a button is clicked, then it will expand. Please help me.

I tried using JavaScript to make the div of the files display hide or show when the button is clicked but it worked for only one file. I want all the files to hide at once and show when button is clicked.

how do I read a the values of an array that is nested inside of an associative array [duplicate]

Here is my dilemma, I am writing a lorem ipsum generator (mostly as a fun pet project). I created a asscociative array containing the ipsum text phrases in an array.

My array structure is as follows

const ipsums = [
  { id: 1,
    name: 'ipsumName',
    sentences: 
      [
      'sentance',
      'sentance',
      'sentence',
      ...
      ...
      ...
      ]
   },
  { id: 2,
    name: 'ipsumName',
    sentences: 
      [
      'sentance',
      'sentance',
      'sentence',
      ...
      ...
      ...
      ]
   },
   ...
   ...
   ...

I am trying to access the individual sentences but when I use console.log see it, I get ‘undefined.

this is my code where I’m trying to display the sentances. I’ve tried a few ways but I get ‘undefined’ in my console window.

const currentIpsum = ipsums.filter(ipsum => ipsum.id == activeIpsum)    
console.log(currentIpsum);

This does display the filtered ipsum but if I try and console log the sentences by doing the following I get ‘undefined’. BTW, the activeIpsum is a value coming in from a form select field which corresponds to the id of the ipsum in the associative array.

console.log(currentIpsum.sentences);

additionally, if I try and add an index to get a specific sentence I get undefined as well.

console.log(currentIpsum[sentences[3]);

Can someone tell me what I’m doing wrong here, Thank you in advanced..

add numbers in an array which are not same ,if same number add 2nd time it can’t add in an array

take a blank array and text box. enter any 3 number 1 by 1 in a text box which is automatically store in a blank array 1 by 1 . and not repeat any number in the array. if you enter 4th number in the text box the 1st one will be removed and 4th will be enter.at the end in array only 3 values should be exist not more or less.

how to match the number with the array so that number do not repeat.

How to make an anchor element trigger a javascript function on left click, but open a new page on middle click?

I noticed that some websites have this functionality, specifically on the Jira website. For example, let’s say I’m on the timeline page with the URL – https://atlassian.net/jira/software/c/projects/AT/boards/31/timeline

On this page, left clicking the name of an issue (an anchor element) triggers the issue details pane on the right, but overall, the browser stays on the same timeline page, and the URL changes to – https://atlassian.net/jira/software/c/projects/AT/boards/31/timeline?selectedIssue=AT-33 – which is the same URL as before, but with an added query parameter.

However, when I middle click the issue, the browser opens a new tab and navigates to the specific issue’s page, an entirely new page with an entirely new URL – https://atlassian.net/browse/AT-33

I’d appreciate if someone can help me understand this behavior in the context of vue.js and vue-router as I would like to replicate this behavior in my single page Vue app.

Want to make Google-search page automatically show more definitions by setting attribute “aria-expanded” to “true” on page load

I always want to see the expanded section when searching for a definition, so I would like it to automatically expand upon loading the page.

Using Tampermonkey to create a userscript that applies to google.com/search?q=meaning+*

From inspecting page elements I have found line
<div class="S8ee5 CwbYXd wHYlTd vk_arc" aria-controls="tsuid_46" aria-expanded="false" data-fbevent="fastbutton" role="button" tabindex="0">

“aria-expanded” changes value when clicking on the button.

Class “S8ee5 CwbYXd wHYlTd vk_arc” has spaces in it, which apparently means multiple classes, so should setAttribute() access by index?

I added window.onload to try to make it run after the page has finished loading in case it tries to access elements prematurely.

My ineffective attempt:

(window.onload = function() {
    'use strict';

    document.getElementsByClassName("S8ee5 CwbYXd wHYlTd vk_arc")[0].setAttribute("aria-expanded", "true");
})();

Angular doesn’t see changes to “input”

I have a component that contains an html form. This form is also additionally processed by custom JavaScript.

This form contains an <input type="button">. Please note that its type is not text, but a button.
This is a context menu for selecting options.

If “input” is of type “text”, then there is no problem. If I start entering any data, then Angular immediately sees it and reacts.

But if “input” is of type “button“, then I have problems. If I click on input, then a context menu pops up where you need to select a parameter, and if I select a parameter, then this parameter is written to the “value” attribute. After selecting an option from the context menu, Angular does not react in any way.

How to make Angular start seeing changes? I want to validate this “input“.

HTML

    <form [formGroup]="loginForm" (submit)="submit()">

    <div class="select__wrap relative">
       <input type="hidden" value="" class="select__title-value">
       <input type="button" formControlName="selectDepartament" id="selectDepartament" class="select__btn" value="">
       <div class="select__box">
          <ul class="select__container">
             <li class="select__title">Real estate</li>
             <li class="select__value">Sell</li>
             <li class="select__value">buy</li>
          </ul>
       </div>
    </div>

    <div class="select__wrap">
       <input type="button" formControlName="selectCity" id="selectCit" class="select__btn" value="">
       <div class="select__box">
          <div class="select__scroll">
             <ul class="select__container">
                <li class="select__value">State of Idaho</li>
                <li class="select__value">State of Iowa</li>
                <li class="select__value">State of Alabama</li>
             </ul>
          </div>
       </div>
    </div>

    <div *ngIf="selectCity.errors?.['required']"> Choose city </div>
    <div *ngIf="selectDepartament.errors?.['required']"> Select State </div>

    </form>

TypeScript

    declare function clickFunction(): void;

    @Component({
      selector: 'app-add',
      templateUrl: './add.component.html',
      styleUrls: ['./add.component.css']
    })
    export class AddComponent implements OnInit{


      loginForm!:FormGroup;




      constructor(private formBuilder: FormBuilder) {
      }

      ngOnInit(): void {

        clickFunction()
        

        this.loginForm = this.formBuilder.group({
          selectCity: ['', {
            validators: [
              Validators.required,
            ]
          }],
          selectDepartament: ['', {
            validators: [
              Validators.required,
            ]
          }]

        });




      }



      get selectCity() {
        return this.loginForm.controls['selectCity'];
      }

      get selectDepartament() {
        return this.loginForm.controls['selectDepartament'];
      }




    }

I also have a custom javascript which also renders the html template

JavaScript

'use strict';
document.addEventListener('DOMContentLoaded', clickFunction);

function clickFunction () {
  
  const select = document.querySelectorAll('.select__wrap');
  
  document.addEventListener('click', (e) => {

    // Клик для select
    select.forEach((item) => {
      const selectBtn = item.querySelector('.select__btn'),
        selectBox = item.querySelector('.select__box'),
        selectContainer = item.querySelectorAll('.select__container'),
        selectTitleValue = item.querySelector('.select__title-value'),
        selectClick = e.composedPath().includes(selectBtn);

      if (selectClick) {
        selectBox.classList.toggle('open');
      }



      // Записать значение в value
      selectContainer.forEach((item) => {
        const selectTitle = item.querySelector('.select__title'),
          selectValue = item.querySelectorAll('.select__value');

        selectValue.forEach((value) => {
          const selectValueClick = e.composedPath().includes(value);

          if (selectValueClick) {
            selectBtn.value = value.textContent;
            selectBox.classList.remove('open');
            if (selectTitle) {
              selectTitleValue.value = selectTitle.textContent;
            }
          } else if (!selectClick || selectValueClick) {
            selectBox.classList.remove('open');
          }
        });
      });
    });


  });

}

Why is my code failing on useEffect whenever I update my JSON data

I have a function that receives JSON data from my server, I use the {jsonData.map((element) => renderComponents(element, jsonData))} function to loop through it and send each object to
renderComponents function along with the full JSON data, and this function has a switch statement with multiple cases for different element.componentType(from the JSON data).

this is the switch statement

function renderComponent(element, jsonData) {
switch (element.componentType) {
    case 'TypeOne':
      return (
        <div>
         </div>
      );
    break;
    
    case 'TypeTwo':

     useEffect(() => {
            console.log("test");
        }, [jsonData]);

    return (
        <div>
         </div>
      );
    break;
}
}

it works the first time it loads, but whenever I use another function to update the jsonData and add a new element of TypeTwo I get an error before the useEffect executes.
I can assure you the updated jsonData is fine and when I load a new TypeOneit gets loaded perfectly, just the issue with TypeTwo

here’s the error code


Warning: React has detected a change in the order of Hooks called by MainFunction. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useState                   useState
2. useEffect                  useEffect
3. undefined                  useEffect
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

this is my json

{
     "title": "MY element",
     "id": 3262405,
     "componentType": "TypeOne",
},
{
     "title": "MY element two",
     "id": 9998454,
     "componentType": "TypeTwo",
}

the issue is with useEffect, it doesn’t get called and the code stops right there

clustering the node.js websocket server with pm2

I try to load balancing the web socket server.

in my project, the clients in the same room must connect to same node.js process.

So i use the pm2 like this.

[server]

// ports will be 7370 ~ 7373
let port = 7370 + parseInt(process.env.pm_id)

server.listen(port, () => {
    console.log(`Server is up on port ${port}!`)
})

const wss = new WebSocketServer({ server: server, path: "/hello" })

wss.on('connection', (ws, req) => {
    ws.on('message', (data) => {
        console.log(` [ ${process.env.name}${process.env.pm_id} ] : ${data} `)
    })
})
[client]

for(let i=0; i<100 ;i++){
    let ws = new WebSocket(`ws://127.0.0.1:${7370 + (i % 4)}/hello`)
    ws.on("open", (data) => {
        let index = i % 4
        console.log(index.toString())
        ws.send(index.toString())
    })
}

As a result of executing with the above code, it was confirmed that there was no problem with socket connection and communication.

I wonder if there will be no problem implementing websocket load balancing in this way.

open the websocket servers to other port for connect directly

Get path with object keys JS

I need get path with object jeys of JS. Function must pass thrught all object, even if he will deep.

Input data:

{
  tree1: {
    node1: 'valOfnode1',
    node2: 'valOfnode2',
    node3: 'valOfnode3',
    node4: {
      node5: 'valOfnode5',
      node6: 'valOfnode6',
      node7: {
        node8: 'valOfnode8',
        node9: 'surprize!',
      },
    }
  }
};

Output data:

[
  ['tree1.node1': 'valOfnode1'],
  ['tree1.node2': 'valOfnode2'],
  ['tree1.node3': 'valOfnode3'],
  ['tree1.node4.node5': 'valOfnode5'],
  ['tree1.node4.node6': 'valOfNode6'],
  ['tree1.node4.node7.node8': 'valOfNode8'],
  ['tree1.node4.node7.node9': 'surprize!'], 
]

Convert yyyyMMdd format to dd/MM/yyyy with Luxon library

I try to parse a date format like ‘20230701’ to ’01/07/2023′ with Luxon library.

I can do this with the following code:

  toDateFormatDDMMYYYY = DateTime.fromFormat(
    dateFormatToTransform,
    'ddMMyyyy'
  ).toLocaleString(DateTime.DATE_SHORT);

toDateFormatDDMMYYYY has the good format (dd/MM/yyyy) when I console.log(). But this code make my jest spectator test fail:

  it('should transform date to format dd/MM/yyyy when BO format is yyyyMMdd', () => {
    spectator = createPipe(`{{'20201130' | formatDateToddMMyyyy}}`);
    expect(spectator.element).toHaveText('30/11/2020'); // KO returns invalid date
  });

I don’t know if it’s my code or my test that has a problem…

Thanks for your help

React Component fails to work properly after refresh

I made a project using the GMap API. The project is aimed at getting the postal code of a place from the latitude and longitude. Everything works fine at first, but if I reload then the API does not give the data. I think the problem is with state management, but am not able to figure it out. Might be the problem with the splice function too. Any help is welcome

const apiKey = import.meta.env.VITE_APP_GMAPS_API_KEY;
Geocode.setApiKey(apiKey);
Geocode.setLanguage("en");
function Loc() {
  const [latitude, setLatitude] = useState(null);
  const [longitude, setLongitude] = useState(null);
  const [address, setAddress] = useState([]);
  const [pin, setPin] = useState(0);
  const [refresh, setRefresh] = useState(false);

  const handleRefresh = () => {
    setRefresh(!refresh);
  };

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(success, error);
  }, []);

  const handleGetAddress = async () => {
    try {
      const response = await Geocode.fromLatLng(latitude, longitude);
      const formattedAddress = response.results[1].formatted_address;
      const addressArray = formattedAddress.split(" ");

      setPin(addressArray[addressArray.length - 2].slice(0, -1));
      setAddress(addressArray.slice(1, 4));
      console.log(addressArray);
    } catch (error) {
      console.error("Error fetching address:", error);
    }
  };
  function success(position) {
    setLatitude(position.coords.latitude);
    setLongitude(position.coords.longitude);
    handleGetAddress();
    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
  }

  function error() {
    console.log("Unable to retrieve your location");
  }
  const center = { lat: latitude, lng: longitude };
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: apiKey,
  });
  if (!isLoaded) return <div>Loading...</div>;

  return (
    <div className="Loc">
      <div className="Loc0">
        <div className="LocFirst">
          <p className="Loc1">Your Current</p>
          <p className="Loc2">Location</p>
        </div>
        <p className="pin">{pin}</p>
        <p className="address">{address}</p>
        <div className="coordinates">
          <p className="coor1">Coordinates :</p>
          <p className="coor2">
            {latitude} , {longitude}
          </p>
        </div>
      </div>
      <div className="icon">
        <img
          src={comp1}
          alt=""
          className="imr"
          onClick={() => {
            navigator.clipboard.writeText(pin);
          }}
        />
        <button onClick={handleRefresh} className="refbut">
          <img src={comp2} alt="" className="imr" />
        </button>
        <img
          src={comp3}
          alt=""
          className="imr"
          onClick={() => {
            navigator.clipboard.writeText(`${latitude} , ${longitude}`);
          }}
        />
      </div>
      <div className="map">
        <img src={map} alt="" className="mapimg" />
        <img src={ellipse} alt="" className="ell" />
      </div>
      <div className="gmap">
        <GoogleMap
          center={center}
          zoom={10}
          mapContainerStyle={{ width: "100%", height: "100%" }}
        >
          <MarkerF position={center} />
        </GoogleMap>
      </div>
    </div>
  );
}

export default Loc;

Thanks for the help