Reactjs images and css displaying locally but not when deployed

When in I run my app locally npm install, everything looks right. But, when I do npm run build, my css and images are not visible.
My app.css looks like this

.Title {
  box-sizing: border-box;
  width: 100%;
  display: flex;
  padding: 1em;
  margin-bottom: 2em;
  background-color: #8A7DDA;
  color: #fff;
}

and I am importing my image with
import image from “./images/logo.png”;
<img src={image} className="App-logo" alt="logo" />
I have tried
<img src={require(image)} className="App-logo" alt="logo" /> and also having the image stored in the public folder

Update information on static HTML website from data.json file

I am trying to add a feature to my website to dynamically update information by pulling it from the data.json file. Currently, I am manually copying and pasting the information into the desired cards, and the process is very tedious, even though it’s the same piece of code. It would be handy if I could just store the information in the data.json file, and the website automatically updates the main HTML code to match the updated information. I have some code written, but it doesn’t work as expected.

Here is the function for updating the content on the website

$(document).ready(function() {
    $.getJSON('./data/data.json', function(data) {

        for (var i = 0; i < data.projects.length; i++) {
            
            $('#project').addClass(data.projects[i].section);
            $('#project-image').attr('src', data.projects[i].image);
            $('#project-title').html(data.projects[i].title);
            $('#project-blurb').html(data.projects[i].blurb);
            $('#project-link').prop('href', data.projects[i].link);
        }  
    });
});

this is the information from the data.json file

"projects": [
        {
            "title": "Stock Game",
            "section": "mobileapp",
            "image": "assets/images/project/StockGame.png",
            "link": "https://github.com/StockGame",
            "blurb": "Stock game is a python program"
        },
        {
            "title": "Real Time Translator",
            "section": "mobileapp",
            "image": "assets/images/project/RT-Translator.jpg",
            "link": "https://github.com/RT-Translator",
            "blurb": "Real Time Translator is a tool that can"
        },

This is the card that I want to dynamically update every time the website is opened, and the data is pulled from the data.json file.

<div class="isotope-item col-md-6 mb-5" id="project" >
                        <div class="card project-card">
                            <div class="row">
                                <div class="col-12 col-xl-5 card-img-holder">
                                    <img id="project-image" class="card-img" alt="image">
                                </div>
                                <div class="col-12 col-xl-7">
                                    <div class="card-body">
                                        <h5 class="card-title" id="project-title"></h5>
                                        <p class="card-text" id="project-blurb"></p>
                                    </div>
                                </div>
                            </div>
                            <div class="link-mask">
                                <a class="link-mask-link" id="project-link"></a>
                                <div class="link-mask-text">
                                    <a class="btn btn-secondary" id="project-link">
                                        <i class="fas fa-eye me-2"></i>View Project
                                    </a>
                                </div>
                            </div><!--//link-mask-->
                        </div><!--//card-->
                    </div><!--//col-->  

Currently, the code only shows one of the 7 projects, and the project-link id also doesn’t work, meaning it doesn’t redirect to my GitHub page. It would be wonderful if you guys could help me figure out how to integrate this with my website and make it not as tedious when I have to delete or add a new project. Thanks in advance.

google.accounts.oauth2.initCodeClient callback is not triggered for google sheets api

Goog morning from Sri Lanka!!! here goes my first question in StackOverflow. I am a novice, and bear with me its total stupid question.

I am trying to get google sheets data for wordpress site using plugin. It seems to me that callback is not triggering. tried searching and reading, but nothing give me answer. Add to that, there is no quickstart guide for google identity services- Google sheets api. all I get from google developer sites is the old way of using api.js, which themselves say its deprecated. GIS migration guide gave me some lime light, but I am stck.

I am not using any frameworks, just plain php and js in wordpress environment. my PHP code is,

<?php
/**
 * Plugin Name: my plugin
 * Description: Gets data from Google Sheets. 
 * Version: 1.0.0
 * Author: Sky the man ([email protected])
 */

function sky_enqueue_scripts() {
    wp_register_script('gapi-script', 'https://apis.google.com/js/api.js', array(), null, true);
    wp_register_script('gis-script', 'https://accounts.google.com/gsi/client', array(), null, true);
wp_enqueue_script('gst-script', plugins_url('GroupStageTable.js', __FILE__), array('gapi-script', 'gis-script'), null, true);

        $translation_array = array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('skyNonce')
    );
    wp_localize_script('gst-script', 'myAjaxObject', $translation_array);
}

add_action('wp_enqueue_scripts', 'sky_enqueue_scripts');



function process_auth_code() {
    check_admin_referer('skyNonce', 'security');
    $code = isset($_POST['code']) ? sanitize_text_field($_POST['code']) : '';
    if (!empty($code)) {
        $google_sheets_data = fetch_data_from_google_sheets($code);
        if (!empty($google_sheets_data)) {
        wp_send_json_success($google_sheets_data);
        } else {
            wp_send_json_error(array('message' => 'Failed to fetch data from Google Sheets'));
        }
    } else {
        wp_send_json_error(array('message' => 'Authentication code is missing or invalid'));
    }

    // Always exit at the end of an AJAX callback
    wp_die();
}

add_action('wp_ajax_process_auth_code', 'process_auth_code');
add_action('wp_ajax_nopriv_process_auth_code', 'process_auth_code');

function my_js_shortcode() {
    ob_start(); // Start output buffering
    ?>
    <div id="google-sheets-data">
        <p id="google-sheets-output">skyoutput</p>
    </div>
    <?php
    return ob_get_clean(); // Return the buffered content
}

add_shortcode('grouptables', 'my_js_shortcode');

?>

and my javascript code GroupStageTable.js is;

var client;
var skyNonce = myAjaxObject.nonce; 
console.log('Nonce', skyNonce);

function initClient() {
    console.log("init client called");
    client = google.accounts.oauth2.initCodeClient({
        
        client_id: '******-******************.apps.googleusercontent.com',
        scope: 'https://www.googleapis.com/auth/spreadsheets.readonly',
        ux_mode: 'popup',
        
        callback: (response) => {
            if (response.error) {
            console.error('Google Auth Error', response.error);
            } else {
            console.log('Google Auth Response', response);
            const code = response.code;
            sendAuthCodeToServer(code, skyNonce);
            }
        }
    });
}
          

function sendAuthCodeToServer(code, skyNonce) {
    console.log('sendAuthCodeToServer Code', code);
     const xhr = new XMLHttpRequest();
    const params = new URLSearchParams({
        action: 'process_auth_code',
        code: code,
        security: skyNonce 
    });
    console.log("auth code sent");
    xhr.open('POST', myAjaxObject.ajax_url, true); 
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    
   xhr.onload = function() {
    var response = JSON.parse(xhr.responseText);
    if (xhr.status === 200 && response.success) {
        console.log("xhr loaded");
        
        gapi.client.sheets.spreadsheets.values.get({
            spreadsheetId: '**********',
            range: "********"
        }).then(function(response) {
            console.log("Data from Google Sheets:", response.result);
        });
        
    } else {
        // Handle errors
        console.error('Error:', response.data.message);
    }
};
xhr.send(params.toString());

}


function updateContent() {
    console.log("updateContent called");
    initClient();
}

document.addEventListener('DOMContentLoaded', function() {
    updateContent(); 
});

console logs only following.

“Nonce 09d3f96985”, “updateContent called”, “init client called”.

tried disabling theme, other plugins and did run on incognito mode but no avail. all 3 scripts are loaded, and there is no console errors.

I am bit lost. what went wrong?

Why doesn’t my map display on my html webpage?

This is my code, I’m using apache and windows 11

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Children's Social and Community Services</title>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
    <header>
        <h1>Children's Social and Community Services</h1>
        <div class="buttons">
            <button class="large-button">1</button>
            <button class="large-button">2</button>
        </div>
    </header>
    <div id="map"></div>

    <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
    <script>
        var layerName = "MyPoints";
        var fileName = "mypoints2.txt";
        var initLon = 152.983737;
        var initLat = -27.500604;
        var zoom = 14;
    </script>
    <script src="openstreetmap.js"></script>
</body>
</html>

I tried to put the map on the right side of the webpage but I can’t see it

Combining to functions javascript to return objects

I have 2 functions that return functions and work well indivdually but I would like to call and use them at the same time.


const mainFactory = function(name, title, description, dueDate) {
    
    return { 
        name: name,
        title: title,  
        description: description,
        dueDate: dueDate, 
        priority: getPriority(),
        
    }
}

function myFactory(){
    let obj = {}
    //Name var to use for the obj name newUser
    let name = document.getElementById("name").value
    obj[(name)] = new Array()

    return obj
}

This is what I have came up with but stuck where to put the properties on 2nd function. I struggle a bit with functions that make object, factory functions


const newFactory = function(name, title, description, duedate){
    const { } = mainFactory(name, title, description, duedate);
    return {
        id: {},
        name: document.getElementById("name").value,
        funct: obj[(name)] = new Array(),
        myFactory() { return id }    
            
        }
    ```
    enter code here

Unable to set default value for array in use state

I want to set default value to my state, but it’s getting undefined. But if I refresh my page values get assigned to categoryIds.


  const si = [...searchParams.getAll("cat")];
  console.log("si", si);

  let sinew = [];
  si.forEach((c) => {
    sinew.push(catmap2.get(c));
  });
  console.log("sinew", sinew);  //print sinew correctly with ids

 

  const [categoryIds, setCategoryIds] = useState(si.length==0? [] : sinew);

  console.log("catids", categoryIds);   //It gives array of same size as sinew but with undefined values

Duplicate API calls are getting called on mutation trigger in React Native RTK-Query

I am triggering mutation on the press of a button but two api calls are going and therefore 2 data entries are getting created.

What can be the possible reason for this?

Please provide any suggestions, I am using React Native.

Following is the endpoint definition.

export const incomeApiSlice = apiSlice
  .enhanceEndpoints({addTagTypes: ['INCOME']})
  .injectEndpoints({
  endpoints: builder => ({
    getIncome: builder.query({
      query: () => ({
        url: '/incomes/',
        method: 'GET',
      }),
      providesTags: ['INCOME']
    }),
    addIncome: builder.mutation({
      query: (payload) => ({
        url: '/incomes/',
        method: 'POST',
        body: payload,
      }),
      invalidatesTags: ['INCOME']
    })
  }),
});

export const { useGetIncomeQuery, useAddIncomeMutation } = incomeApiSlice;

And this is how I am using it in the component.

const handleAddIncome = async (values) => {

    console.log("AddIncomeForm: values:", values);

    try {
      // const response = await createIncome(values).unwrap();
      const response = await createIncome(values)

      console.log("AddIncomeForm: handleAddIncome::response: ", response);

      typeof onSubmit === 'function' && onSubmit();

    } catch (error) {

      console.log("AddIncomeForm: handleAddIncome::error: ", error);

    }

  }

  // code omitted

<Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={handleAddIncome}
    >
      {
        function AddIncomeFormik(formik) {

// code omitted


<ButtonAR
  buttonStyles={{ paddingVertical: 0 }}
  containerStyles={{ marginBottom: RFValue(32) }}
  onPress={formik.handleSubmit}
  disabled={!formik.isValid || !formik.dirty || isLoading}
  loading={isLoading}
>
  Submit
</ButtonAR>


// code omitted

Any kind of help is appreciated.

Accessing device accelerometer in web javascript on a local file on smartphone

I’m wondering why my smartphone isn’t able to access the accelerometer from javascript. I loaded the file onto the smartphone’s (android) files, but no motion data is being read.

It works fine on my tablet, but the same script doesn’t work on my android phone. I’m using the function:

ondevicemotion = function(e) {

}

It does nothing on the android phone. Anybody know why this is?

I tried loading the file directly onto the android smartphone. I expected the script to work the same that it does on my tablet, but no device motion data is read. I also tried on an iphone and it did not work.

Issue with sap.ui.mdc.FilterField and DateTime data type

I’m facing an issue filtering a DateTime field using sap.ui.mdc.FilterField and dataType sap.ui.model.type.DateTime.

My files are very similar to the official FilterBar sample provided here: https://openui5.hana.ondemand.com/entity/sap.ui.mdc/sample/sap.ui.mdc.demokit.sample.TableFilterBarJson/code

But here are the specifics:

My FilterField in the main XML view looks like this:

<mdc:FilterField
    delegate="{name: 'sap/ui/mdc/field/FieldBaseDelegate'}"
    label="{i18n>createdOn}"
    propertyKey="created_on"
    dataType="sap.ui.model.type.DateTime"
    conditions="{$filters>/conditions/created_on}"
    maxConditions="1" />

My PropertyInfo configuration is as follows:

{
    name: "created_on",
    label: i18nModel.getProperty("createdOn"),
    visible: true,
    path: "created_on",
    dataType: "sap.ui.model.type.DateTime",
    formatOptions: {
        source: {
            pattern: 'yyyy-MM-ddTHH:mm:ss X',
        },
        UTC: true,
        style: 'medium'
    },
    maxConditions: 1
}

My JSONModel (retrieved from a PHP backend) bound to the table is structured like this:

[{"created_on":"2023-11-04T18:17:03+0100"}]

The date is correctly displayed in the table column, the FilterField valueHelp shows a calendar for selecting the date and time, and the selected value is correctly applied to the FilterField.

However, when I apply the filter, no rows are returned, not even the ones that should match the filter criteria.

I’ve tried several things, such as changing the pattern and adding format options directly in the FilterField tag within the XML view, among others.

Could you help me initiate a new ‘investigation’ into this issue? Even if we try some things I’ve already attempted, it would help to ‘check’ them off as non-working solutions.

Thanks!

Us there any major difference between the MongoDB ObjectId and npm package UUID? how can I use one instead of the other

Since the ObjectId is the default way MongoDB identify document is there anyway to replace it with UUID?

tried replacing the ObjectId with UUID()
also I want to know the key difference between the ObjectId of the MongoDB and also the npm package UUID, what are the advantages and also the disadvantages of using one of the method instead of the other

I am using Node and Express for my backend server

paypal payment confirmation popup is closed without any result

I integrating paypal payment to a web application, and i am using a spring boot application as backend server, the createOrder function is executed and an orderId is returned…
but when I confirm the payment in the popup below:

enter image description here

it just disappears and nothing happens.

If I understood well normally the onApprove function should be executed if everything goes well but it is not the case, and i do not know why.

Here is my code:

FrontEnd Javascript:

createOrder(data, actions, cartInfo) {
        console.log('CREATE ORDER DATA: ', data);
        console.log('CREATE ORDER ACTIONS: ', actions);
        console.log('CREATE ORDER CARTINFO: ', cartInfo);
        const totalAmount = parseFloat(cartInfo.total).toFixed(2);

console.log('############### ', totalAmount);
        // Order is created on the server and the order id is returned
        return fetch("http://127.0.0.1:8102/paypal/create-order", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            // use the "body" param to optionally pass additional order information
            // like product skus and quantities
            body: JSON.stringify({
                intent: "CAPTURE",
                purchase_units: [
                    {
                        items: cartInfo.items,
                        amount: {
                            currency_code: 'CAD',
                            value: `${totalAmount}`,
                        },
                    },
                ],
            }),
        })
        .then((response) => response.json()).catch(error => {
            console.log('ERROR: ', error);
        })
        .then((order) => order.id);
    }
    onApprove(data, actions) {
        console.log('CREATE ORDER DATA ONAPPROVE: ', data);
        // Order is captured on the server
        return fetch("http://127.0.0.1:8102/paypal/capture-order/{data.orderID}", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                orderID: data.orderID
            })
        })
        .then((response) => {
            console.log('$$$$$$$ RESPONSE: ' , response);
            response.json();
        }
        );
    }

    onSuccess(details, data) {
        console.log('$$$$$$$$$$$$$ SUCCESSS');
        console.log('$$$$$$$$$$$$$ data ', data);
        console.log('$$$$$$$$$$$$$ details ', details);
    }

The Java backend code:

@PostMapping(value = "/create-order", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object createOrder(HttpServletRequest request, @RequestBody String order) {

        RestTemplate restTemplate = new RestTemplate();
        String accessToken = "";
        try {
            accessToken = tokenHelper.generateAccessToken();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + accessToken);
        headers.add("Content-Type", "application/json");
        headers.add("Accept", "application/json");
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<String>(order, headers);
        try {
            ResponseEntity<Object> response = restTemplate.exchange(baseUrl.concat("/v2/checkout/orders"), HttpMethod.POST, entity, Object.class);
            if (response.getStatusCode() == HttpStatus.CREATED) {
                log.info("ORDER CAPTURE");
                return response.getBody();
            } else {
                log.error("FAILED CAPTURING ORDER");
                return "Unavailable to get CAPTURE ORDER, STATUS CODE " + response.getStatusCode();
            }
        } catch (HttpClientErrorException ex) {
            log.error(ex.getMessage());
            return null;
        }

    }

    @PostMapping(value = "/capture-order/{orderId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object captureOrder(@PathVariable("orderId") String orderId) {
        System.out.println("################## ORDER CAPTURED " + orderId);
        return null;
    }

Any help or suggestion are much appreciated.

my first react app is throwing this error : Uncaught SyntaxError SyntaxError: Unexpected token ‘<'

I am new to front-end & have just begun react js, (learning in VS code) I’ve setup my basic environment but when executing the 1st default “page.js” file the following error is being thrown:

C:Program Filesnodejsnode.exe .apppage.js
Process exited with code 1
Uncaught SyntaxError SyntaxError: Unexpected token ‘<‘

The code in my page.js file

import React from 'react'

const page = () => {
return (
    <div> page </div>
 )
}

export default page

given i am new to this environment I just can’t seem to understand what’s wrong here nor am I able to get any answers on how to fix this over the net, if someone can explain what is the problem & how to fix it & why is it happening, it would be very helpful.
Thanks

Crowdsourcing or Fake data ( random / generated)?

Screenshot of the web pages aimed for mobile use

Hi all,
I have to do a group project for school. I’ve come up with this design for the pages. At first I thought of going for this idea ’cause it looked like it wouldn’t be hard. As if we could just automate going to Walmart’s site, right-click on inspect, and find divs by keywords to retrieve and display them on the web app. We’ve told our instructor that the web app compares prices of groceries from supermarkets to help find the cheapest ones ( sorting them from the cheapest ). She didn’t oppose to it. Now that we got to the point to do the data, she said that to use API it seems too hard for your technical knowledge (we’re only on our 1st term) nor will it be free to access the API. Wtf do we do.. She said we can either use crowdsourcing or use fake data be it randomized or generated by sites like mockaroo.

For crowdsourcing, I’d need to change the pages again, but that won’t be a problem, shouldn’t take that long. But my concern is more about the web app looking unfinished since we’d have no data in the beginning right? Since we won’t have lots of users / volunteers willing to make posts when they find the cheapest stuff in xyz supermarket. We need to present this at the end of the term, which is just in another 4-5 weeks. And unfortunately, our business communication instructor also wants to grade our presentation, and wants us to make a report based on our project, so we might fail these 2 courses if we fail this.

As for the fake data, the things she told us to do just sound like too much to do within our deadlines, and too complicated for us to even comprehend. At first, I also didn’t wanna use “FAKE” data, ’cause what’s the point then? But what other choice do we even have at this point, and our instructor told us that if we were to use fake data, the aim is to make a prototype for when we’re ready to use actual data someday in the future, so we’re just setting everything up and can just replace it later on in the future if we still want to. So I’m warming up and leaning towards fake data now.. the good thing about this is we don’t need to change our UI / pages either, ’cause frankly speaking, making designing & wireframes don’t take long, but coding them in html and css take quite some time for a group project. And sadly my teammates aren’t pulling their weight, not even responding fast. I’m screwed and regret everything now.

Any suggestions would be appreciated.

And just in case anyone wanna know what she told us,
This was what she told us :
“Another option is to create a database of fake prices of a small collection of products, for two supermarkets. Use this database to implement your original idea, with the assumption that hypothetically the JSON, or the data can be web-scraped or accessed directly from an API when your business/company decides to go forward with the idea.
you can pretty much keep your same UI screens, and your goal would be to create a prototype that proves your initial concept, of guiding me to go to which store for milk, which store for eggs, etc. Keep your collection of products small for now. To mimic the idea of variable prices, you can have a JS that creates random prices for a small group of staple items, so that eventhough it’s “fake data”, you can still have a random aspect of the prices. We are not concerned with the accuracy of the prices.
When we read from api, json is one of the formats we can get (there’s also others like xml etc). One day if you do get from Walmart api, the format may be json but it’s not necessarily getting a big file with tons of product info, you might just be getting something specific for say apples, depending on the api call that you make. Json is a flexible format.
If you do make a fake Json file (say with mockeroo), say two supermarkets and each has 10 producst, then you can read it into firestore one time only. Afterwards each time (or each day?) the app is loaded you can have a js file that goes into the firestore field for price and gives/assign it a random number. That way you can test your algorithm for finding the cheapest apple for today, and tell me which store to go to, today. It’s timing sensitive.”

HTML canvas keep on rendering line, even after I cleared it

I am trying my hand on building a drawing app in React using HTML Canvas element.

import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
///*[EN ROUGH]*/import rough from 'roughjs';

///*[EN ROUGH]*/const generator = rough.generator();

const createElement = (x1, y1, x2, y2, type) => {
  return { x1, y1, x2, y2, type };
};

const drawElement = (context, element) => {
  if (element.type === "connect") {
     context.moveTo(element.x1, element.y1);
     context.lineTo(element.x2, element.y2);
     context.stroke();
    ///*[EN ROUGH]*/const line = generator.line(element.x1, element.y1, element.x2, element.y2);
    ///*[EN ROUGH]*/context.draw(line);

  }
};

function App() {
  const [elements, setElements] = useState([]);
  const [drawing, setDrawing] = useState(false);

  useLayoutEffect(() => {
    const canvas = document.getElementById("canvas");
    const context = canvas.getContext("2d");

    context.clearRect(0, 0, canvas.width, canvas.height);
    ///*[EN ROUGH]*/const context = rough.canvas(canvas);

    //redraw all the components on re-render
    elements.forEach((element) => {
      drawElement(context, element);
    });
  });

  const handleMouseDown = (event) => {
    setDrawing(true);
    const { clientX, clientY } = event;

    const element = createElement(
      clientX,
      clientY,
      clientX,
      clientY,
      "connect"
    );
    setElements((prevState) => [...prevState, element]);
  };

  const handleMouseMove = (event) => {
    if (!drawing) return;
    const { clientX, clientY } = event;
    //index of the last element that was selected
    const lastElemIndex = elements.length - 1;
    const { x1, y1 } = elements[lastElemIndex];
    const updatedElement = createElement(x1, y1, clientX, clientY, "connect");

    //overwrite the previous element with the new x2, y2 coordinates of mouse move
    const elementsCopy = [...elements];
    elementsCopy[lastElemIndex] = updatedElement;
    setElements(elementsCopy);
  };

  const handleMouseUp = () => {
    setDrawing(false);
  };

  return (
    <canvas
      id="canvas"
      width={window.innerWidth}
      height={window.innerHeight}
      onMouseDown={handleMouseDown}
      onMouseUp={handleMouseUp}
      onMouseMove={handleMouseMove}
    >
      Canvas
    </canvas>
  );
};

export default App;

When I run this code, it produces this output when I click and drag mouse:

enter image description here

When I enable RoughJS to draw instead of normal canvas, the line works fine. RoughJS code can be enabled by removing comments EN ROUGH. I am totally lost why it’s happening.