How do I make my navigation icon appear in mobile mode for a ReactJS and TailwindCSS app

I’ll appreciate help with my bug.
I have a ReactJS and TailwindCSS application. The navigation displays fine in desktop mode but in mobile mode, the navigation or hamburger icon doesn’t appear.

My App.jsx file is in the path: travelworld/src/component/Navbar.jsx

import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import { FaTimes, FaBars } from 'react-icons/fa'

const Navbar = () => {
    const [showNavigationForMobile, setShowNavigationForMobile] = useState(false);
    return (
        <nav className='fixed m-4 top-0 right-0 left-0 shadow-lg z-50 bg-white'>
            <div className='container px-4 flex justify-between items-center h-16'>
                <h3 className='text-2xl font-bold'>Travel</h3>
                {!showNavigationForMobile && (
                <div className='md:show flex space-x-4 text-sm font-bold items-center'>
                    <Link to="/" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>Home</Link>
                    <Link to="/gallery" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>Gallery</Link>
                    <Link to="/contact" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>Contact</Link>
                    <Link to="/about" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>About</Link>
                    <button className='py-2 px-6 border bg-gray-400'>Login</button>
                </div>
                )}
                <div className='md:hidden'>
                    <button onClick={() => setShowNavigationForMobile(!showNavigationForMobile)}>
                    {showNavigationForMobile ? <FaTimes /> : <FaBars />}
                    </button>
                </div>
            </div>
            {showNavigationForMobile && (
            <div className='flex space-y-6 py-4 flex-col bg-white items-center'>
                <Link to="/" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>Home</Link>
                <Link to="/gallery" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>Gallery</Link>
                <Link to="/contact" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>Contact</Link>
                <Link to="/about" className='px-6 py-2 hover:bg-gray-600 hover:text-white'>About</Link>
                <button className='py-2 px-6 border bg-gray-300'>Login</button>
            </div>
            )}
        </nav>
    )
}

export default Navbar

My Home.jsx file is in the path: travelworld/src/pages/Home.jsx

import React from "react";
import PopularDestination from '../component/PopularDestination';
import Services from '../component/Services';
import Clients from '../component/Clients';

const Home = () => {
    return (
        <>
            <div className='relative h-screen bg-cover bg-center' style={{backgroundImage : "url('/images/hotel_paris.jpg')"}}>
                <div className='absolute inset-0 bg-black bg-opacity-50 flex flex-col items-center justify-center'>
                    <h1 className='text-4xl md:text-6xl font-bold text-white mb-4'>Explore the world with us</h1>
                    <p className='text-lg md:text-2xl text-white mb-8'>Discover amazing places at exclusive deals</p>
                    <button className='border text-white px-6 py-2 rounded-full text-lg md:text-xl hover:bg-blue-500 transform transition duration-300 hover:scale-105'>Get started</button>
                </div>
            </div>
            <PopularDestination />
            <Services />
            <Clients />
        </>
    );
}

export default Home;

My App.jsx file is in the path: travelworld/src/App.jsx

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./pages/Home";
import Navbar from "./component/Navbar";

const App = () => {
  return (
    <BrowserRouter>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />}></Route>
      </Routes>
    </BrowserRouter>
  );
};

export default App;

My package.json file is in the path: travelworld/package.json

{
  "name": "travelworld",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-icons": "^5.3.0",
    "react-router-dom": "^6.26.0"
  },
  "devDependencies": {
    "@eslint/js": "^9.8.0",
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "@vitejs/plugin-react": "^4.3.1",
    "autoprefixer": "^10.4.20",
    "eslint": "^9.8.0",
    "eslint-plugin-react": "^7.35.0",
    "eslint-plugin-react-hooks": "^5.1.0-rc.0",
    "eslint-plugin-react-refresh": "^0.4.9",
    "globals": "^15.9.0",
    "postcss": "^8.4.41",
    "tailwindcss": "^3.4.9",
    "vite": "^5.4.0"
  }
}

onClick does not work on first click in React

I have a button that shows/hides an element when click but it does not work on first click but it works on the following clicks. I’m expecting it to work on the first click.

import { useState } from "react";

function myComponent() {

    const [elem, setElem] = useState(false);
    const handleClick = () => {
        setElem(true);
        if(elem) {
            document.getElementById('item').classList.toggle('show');
            document.getElementById('item').classList.toggle('hide');
        }
    }

    return (
        <button onClick={handleClick}>touch me</button>
    );
}

export default Navbar;

What I imagine that is happening under the hood is that when the button is clicked it will set the elem to ‘true’ then the ‘if’ statement runs because the elem is ‘true’. I also tried to console.log the elem outside and inside the if statement and it shows false and the if statement doesn’t run on the first click. I could just remove the if statement and not use a State but I want to do other things if the button is clicked. Can someone explain to me what really is happening here under the hood? Thank you!

calculate the input value and update 3 results when click calculate button with JavaScript

I have 4 calculations that I have set up to spit out results when an integer 1-100 is typed into the input. right now, the values automatically update as I am typing, but I want them to wait until the calculate button is clicked. I can’t seem to figure out what I did wrong, or what I am missing.

let phoneOutput = document.getElementById("rc-phone");
let carOutput = document.getElementById("rc-car");
let trashOutput = document.getElementById("rc-trash");
let monthlyCost = document.getElementById("monthly-cost");
let input = document.getElementById("customPercent");
let ggrResults = document.querySelector("#customPercent");

ggrResults.addEventListener('input', e => adjustData(e.target.value)) // had to add in .value in order to extract the text from the input
const adjustData = (a) => {
//   convert value from input text to number in order to calculate
  const numberConvert = Number(a);
  const decimal = numberConvert/100;
  const monthlyCostFormula = (8000 * decimal) * (.026/12);
  const trashBagFormula = 243 * decimal;
  const milesDrivenFormula = 14294 * decimal;
  const phonesChargedFormula = 368949 * decimal;
  monthlyCost.innerHTML = monthlyCostFormula.toFixed(2);
  trashOutput.innerHTML = Math.round(trashBagFormula);
  carOutput.innerHTML = Math.round(milesDrivenFormula);
  phoneOutput.innerHTML = Math.round(phonesChargedFormula);
}
<form method="post">
  <input id="customPercent"  type="text" placeholder="custom" />
  <button type="submit" onclick="return(adjustData());" id="submit">Calculate</button>
</form>
<div>
  <h6>Equal to Removing</h6>
  <span style="font-size: 28px; font-weight: bold; font-family: sans-serif;" id="rc-trash">100</span><br>
  <span class="green-text small-txt">Trash Bags of Waste from the Environment</span>
</div>
<div>    
  <h6>Equal to offsetting</h6>
  <span style="font-size: 28px; font-weight: bold; font-family: sans-serif;" id="rc-car">20</span><br>
  <span class="green-text small-txt">Gas-Powered Miles Driven</span>
</div>
<div>
  <h6>Equal to offsetting</h6>
  <span style="font-size: 28px; font-weight: bold; font-family: sans-serif;" id="rc-phone">500</span><br>
  <span class="green-text small-txt">Smartphones Charged</span>
</div>
<div>
  <h4 class="heading-4">Estimated Monthly Cost <a href="#" data-toggle="tooltip" title="This will have an explanation"><i class="fa fa-info-circle gray"></i></a></h4>
  <span style="font-size: 28px; font-weight: bold; font-family: sans-serif;">$<span id="monthly-cost">15.00</span></span>
  <h5>per month</h5>   
</div>

How to Change Language Without Redirecting Pages with Next.js?

I provide multi-language support to the Nextjs project using the next-i18next package. English and German languages.

There is a fixed menu named Home Page, Categories, Contact. The names of these menus need to be changed by changing the language with the help of a button.

i18n.changeLanguage(‘en’); With the method, the change is not reflected on the screen. State is not updated. I see that it has changed with console.log.

const { i18n } = useTranslation();
const router = useRouter();
function changeLanguage(language) {
  i18n.changeLanguage(language);
  router.push(router.asPath, undefined, { locale: language });
}

By using the method, it works and the state changes when the page is directed to /blog/en and blog/de.

Can’t the language be changed without refreshing the page and redirecting (router.push())?
Am I using the wrong package?

Extract thermal data from JPEG using JS

I use FLIRONE PRO to take the picture and save thermal data in JPEG file. I want to display it on a website. Is there a way to extract the thermal data in the JPEG file using JS in React App?

Here is a test JPEG picture that contains the thermal data.

I tried using exif reader to parse the meta data. But it seems the thermal data in not in meta data.
exif data parsed from above test JPEG picture.

Unable start React native project at first time after installation

I’m new on react native, before i started dev in, i read the official doc of react native. in docs, it start with expo framework. i created react native project with this command

create-expo-app --template

and select blank option. after project initialization finish. i try to run it and got error like below

enter image description here

i also installed dependency for web

pnpm install react-native-web react-dom @expo/metro-runtime

anyone can help me how i can to fix that??

Unable to resolve "../../App" from "node_modules/.pnpm/[email protected]_@[email protected]_@[email protected]_@[email protected]_/node_modules/expo/AppEntry.js" ```

I’m trying to extract data from this API using Node.js

I’m trying to extract data from this API and this is what the structure looks like:

{
  "wait_time": {
    "port": [
      {
        "port_id": "240201",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "31",
              "expected_delay": "31"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "5",
              "expected_delay": "6"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "7",
              "expected_delay": "8"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "7",
              "expected_delay": "6"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "7",
              "expected_delay": "7"
            }
          ]
        }
      },
      {
        "port_id": "535502",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "5",
              "expected_delay": "5"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "13",
              "expected_delay": "13"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "74",
              "expected_delay": "68"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "5",
              "expected_delay": "5"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "4",
              "expected_delay": "5"
            }
          ]
        }
      },
      {
        "port_id": "230403",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "8",
              "expected_delay": "7"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "5",
              "expected_delay": "5"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "21",
              "expected_delay": "20"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "4",
              "expected_delay": "4"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "4",
              "expected_delay": "4"
            }
          ]
        }
      },
      {
        "port_id": "230302",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "1",
              "expected_delay": "1"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "1",
              "expected_delay": "1"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "5",
              "expected_delay": "5"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "2",
              "expected_delay": "2"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "4",
              "expected_delay": "4"
            }
          ]
        }
      },
      {
        "port_id": "250602",
        "wait_time_event": {
          "update_time": "2024-08-20T15:30:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "0",
              "expected_delay": "0"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "8",
              "expected_delay": "9"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "11",
              "expected_delay": "12"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "0",
              "expected_delay": "0"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "0",
              "expected_delay": "0"
            }
          ]
        }
      },
      {
        "port_id": "230502",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "3",
              "expected_delay": "3"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "8",
              "expected_delay": "8"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "8",
              "expected_delay": "8"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "12",
              "expected_delay": "11"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "20",
              "expected_delay": "19"
            }
          ]
        }
      },
      {
        "port_id": "230404",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "65",
              "expected_delay": "55"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "12",
              "expected_delay": "21"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "17",
              "expected_delay": "18"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "0",
              "expected_delay": "0"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "30",
              "expected_delay": "24"
            }
          ]
        }
      },
      {
        "port_id": "240203",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "11",
              "expected_delay": "14"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "19",
              "expected_delay": "12"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "26",
              "expected_delay": "26"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "14",
              "expected_delay": "18"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "7",
              "expected_delay": "6"
            }
          ]
        }
      },
      {
        "port_id": "535503",
        "wait_time_event": {
          "update_time": "2024-08-20T15:40:00",
          "lane": [
            {
              "type": "Commercial",
              "sub_type": "Aduana",
              "actual_delay": "12",
              "expected_delay": "8"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP FAST",
              "actual_delay": "10",
              "expected_delay": "10"
            },
            {
              "type": "Commercial",
              "sub_type": "CBP Standard",
              "actual_delay": "10",
              "expected_delay": "10"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS FAST",
              "actual_delay": "10",
              "expected_delay": "10"
            },
            {
              "type": "Commercial",
              "sub_type": "DPS Standard",
              "actual_delay": "10",
              "expected_delay": "10"
            }
          ]
        }
      }
    ]
  }
}

When I want to print the data to the console I get this:

"230404"
{
  wait_time: {
    port: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object]
    ]
  }
}

I want to acess the actual delay in port_id. This is what my code looks like to print the whole structure, but I’m not sure how to access the data:

const url=
    ' https://bciswebapi.azurewebsites.net/api/segmentcommercial'

//https://bciswebapi.azurewebsites.net/api/segmentpassenger
//'https://bwt.cbp.gov/api/waittimes'

async function getData(){
    const response = await fetch(url)
    const data= await response.json()
        .then(data=>console.log(data))


}

getData()

Only part of my website appears when I use history.back() after waiting for a few minutes

I am using an HTMX-like solution in my website with vanilla JS. So I have a part of my website that I update with new HTML. The problem is that when I use the history.back() method on another page of my site and wait a few minutes I can only see the content the last request made. So like the content of 15 posts. Nothing else of my page. If I don’t wait a lot everything works perfectly. And when I press CTRL-U I can also only see the content of the last request, not my whole page.

Here is the relevant code:

function updateContent(replace=false) {
    if (start > amount){
        return;
    }

    if (!isFetching) {
        isFetching = true;
        document.getElementById('loading').style.display = 'flex'; // Show the loading animation

        fetch(window.location.href.toString(), {
            headers: {
                'update-content': true,
                'start': start
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error: ${response.status}`);
            }
            if (start === 0) {
                amount = parseInt(response.headers.get('amount'));
                document.getElementById('amount').innerHTML = amount + " találat";
                let kayak_km = response.headers.get('kayak_km') || 0;
                if (kayak_km !== null){
                    const element = document.getElementById('km');
                    if (element){
                        element.innerHTML = kayak_km + " km kajak az időszakban";
                    }
                }
            }
            return response.text();
        })
        .then(text => {
            if (!replace) {
                document.getElementById('content').innerHTML += text; }
            else {
                document.getElementById('content').innerHTML = text;
            }
            start += startIncrement;
            isFetching = false;
            document.getElementById('loading').style.display = 'none'; // Hide the loading animation
        })
        .catch(() => {
            isFetching = false;
            document.getElementById('loading').style.display = 'none'; // Hide the loading animation in case of error
        });
    }
}

window.addEventListener('scroll', debounce(function () {
// Get scroll position
    const scrollTop = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;

    // Check if the user has scrolled to the bottom
    if (scrollTop + windowHeight >= documentHeight - 100) {
        updateContent();
    }
    }, 100));

function initForm(formId)
{
    document.getElementById(formId).addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent the form from reloading the page
        const formData = new FormData(this);
        const queryParams = new URLSearchParams(formData).toString();
        start = 0;
        history.pushState(null, '', window.location.pathname.toString() + "?" + queryParams);
        showOrHideKayakKm();
        updateContent(true);
});
}

function resetParams(formId){
    let url = new URL(window.location);
    url.search = '';
    start = 0;
    document.getElementById(formId).reset();
    history.pushState(null, '', url);
    showOrHideKayakKm();
    updateContent(true);
}

I have tried looking into popState methods, but I need the site not to reload when the user goes back.

How can I count values ​of a json string where 2 values ​are equal [duplicate]

How can I count values ​​of a json string where 2 values ​​are the same?

I have some entries that have a date and a number. If the date and the number are the same, the values ​​should be counted.

How can I do this with JavaScript?

Unfortunately, I don’t have the approach, so I haven’t been able to try anything yet.

JSON:

[date] {
     [id]{
        [date]
        [number]
        [etc.]
     }
  }

Kafka deployed on Heroku giving error “Not authorized to access topics”

I have deployed a Kafka on Heroku server.
The problem is that I am getting connected to the Kafka server on Heroku. The connection is successful and I am able to see all of my available topics on the Heroku server.
But when I try to produce message on one of the topics. It gives an error
{“level”:”ERROR”,”timestamp”:”2024-08-20T14:52:25.903Z”,”logger”:”kafkajs”,”message”:”[Connection] Response Metadata(key: 3, version: 6)”,”broker”:”MY_BROKER”,”clientId”:”MY_CLIENT_ID”,”error”:”Not authorized to access topics: [Topic authorization failed]”,”correlationId”:1,”size”:627}

This is how i am creating the client

kafka = new Kafka(
        {
         clientId: "deanon-tool",
         brokers: [
           "ec2-54-77-1-249.eu-west-1.compute.amazonaws.com:9096",
           "ec2-54-72-228-10.eu-west-1.compute.amazonaws.com:9096",
           "ec2-52-48-167-48.eu-west-1.compute.amazonaws.com:9096",
           "ec2-34-246-78-10.eu-west-1.compute.amazonaws.com:9096",
           "ec2-34-242-239-67.eu-west-1.compute.amazonaws.com:9096",
           "ec2-34-246-81-10.eu-west-1.compute.amazonaws.com:9096",
           "ec2-34-246-80-221.eu-west-1.compute.amazonaws.com:9096",
           "ec2-52-214-17-78.eu-west-1.compute.amazonaws.com:9096",
           ],
         ssl: {
           rejectUnauthorized: false,
           ca: [fs.readFileSync("./ca-cert.pem", "utf-8")],
           key: fs.readFileSync("./client-key.pem", "utf-8"),
           cert: fs.readFileSync("./client-cert.pem", "utf-8"),
          },
        });

This is the code where it throws error

   public async testConnection(topic: string): Promise<void> {
        const producer = this.kafka.producer();
        console.log("Topic", topic);
        try {
            console.log("Connecting to Kafka...");
            await producer.connect();
            console.log("Connected successfully. Attempting to send a test message...");
            await producer.send({
                topic: topic,
                messages: [{ value: "Test message" }],
            });
            console.log("Test message sent successfully");
        } catch (error) {
            console.error("Error during Kafka test:", error);
        } finally {
            await producer.disconnect();
        }
    }

The “Connected successfully” log is logged and after that it crashes on the producer.send()

click element with xpath in iframe with javascript

I want to click on an element in the iframe by xpath with coding. Is there a javascript code for this?

I found this code:

<html> <body> <iframe id="test" source="test.html"> </iframe> </body> </html>

In scripts:

$('#test').contents().find('BUTTON ID').click(function(){ alert("works") });

but i want to click with xpath not by id.

Twitter API to fetch real-time Likes, Comments, Follows, Reposts from my twitter handle? X Enterprise API is too costly

I’m working on a scoring web app that tracks activity on my X (formerly Twitter) handle, such as real-time Likes, Comments, Follows, and Reposts.

My Use case is that anyone who connects his twitter on my website his score will be shown as per his activity on my twitter handle.

The X Enterprise API is too expensive for my budget($42,000). I’m looking for a more affordable solution to fetch this data in real time. Does anyone have suggestions for cost-effective alternatives or workarounds?

Unexpected end to JSON input

I am working on a UI interface for an Automated plant growth chamber and it involves a Raspberry Pi to which an Arduino nano is connected.

I am using a VEML7700 and DHT11 sensors and these are connected to my Arduino to take readings. These readings are taken by the Raspberry pi through serial communication. I have a python script on the Raspberry pi that will send the data to a database and store them in there.

I also have code in js and php that work together to display the readings in JSON format on a webpage. I have a light control page that will take inputs from the user and the added code to my js and php to handle sending the input values into a the same database but a different table. Now when I type this in there I get an error that says

“Error: Unexpected end to JSON input”

Also the input values form the light control page never get to the database. I suspect it may have something with my js and php so i will just paste my code below.

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $result = $conn->query("SELECT id, foo FROM some-table DESC LIMIT 10");

    $data = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $data[] = [
                'id' => $row['id'],
                'foo' => $row['foo'],
            ];
        }
    }

    echo json_encode($data);
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $lux = intval($_POST['lux']);
    if ($lux >= 0 && $lux <= 255) {

        $sql = "INSERT INTO luxvalues (setpoint) VALUES ($lux)";

        if ($conn->query($sql) === TRUE) {
            echo json_encode(['message' => 'Setpoint value stored successfully.']);
        } else {
            echo json_encode(['message' => 'Error: ' . $conn->error]);
        }
    } else {
        echo json_encode(['message' => 'Error: Please enter a value between 0 and 255.']);
    }
}
document.addEventListener('DOMContentLoaded', function() {
    // Function to fetch and display sensor data
    function fetchSensorData() {
        fetch('combined_script.php') // Use the combined PHP script
            .then(response => response.json())
            .then(data => {
                const table = document.getElementById('dataTable');
                if (table) {
                    // Clear existing table rows except the header
                    const rowCount = table.rows.length;
                    for (let i = rowCount - 1; i > 0; i--) {
                        table.deleteRow(i);
                    }

                    // Log data to inspect it
                    console.log(data);

                    data.forEach(item => {
                        const row = table.insertRow();
                        const idCell = row.insertCell(0);
                        const tempCell = row.insertCell(1);
                        // etc

                        idCell.textContent = item.id;
                        tempCell.textContent = item.temperature;
                        // etc
                    });
                }
            })
            .catch(error => {
                console.error('Error fetching sensor data:', error);
            });
    }

    if (document.getElementById('dataTable')) {
        fetchSensorData();

        setInterval(fetchSensorData, 15000);
    }

    // Light Control form submission
    const luxForm = document.getElementById('luxForm');
    if (luxForm) {
        luxForm.addEventListener('submit', function(event) {
            event.preventDefault();
            const lux = document.getElementById('lux').value;

            fetch('combined_script.php', { // Use the combined PHP script
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `lux=${lux}`
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('response').textContent = data.message;
            })
            .catch(error => {
                document.getElementById('response').textContent = 'Error: ' + error.message;
            });
        });
    }
});

It is important to mention that i am using apache2, mariadb and phpmyadmin for this project.
Can anyone help me with this problem.

To make sure only JSON is returned, add a fallback to catch any unexpected output before the JSON response i made the following adjustmets to the part that handles the inputed values

    if ($lux >= 0 && $lux <= 255) {
        $sql = "INSERT INTO luxvalues (setpoint) VALUES ($lux)";
        if ($conn->query($sql) === TRUE) {
            $output = json_encode(['message' => 'Setpoint value stored successfully.']);
        } else {
            $output = json_encode(['message' => 'Error: ' . $conn->error]);
        }
    } else {
        $output = json_encode(['message' => 'Error: Please enter a value between 0 and 255.']);
    }

    echo $output;
}

Upon making these changes, i now get an error that says
‘Error: Network response was not ok’
Also the php adjustmets failed to log the php-errors into a file for me to have a better idea of what is happening. It this point i have been at it for two days and i am humbly requesting asistance with this.

Setting Up Webpack for a React Project

Setting Up Webpack for a React Project – Need Help with Error

I’m in the process of setting up Webpack for my React project using npm, but I’m encountering an error that I can’t seem to resolve. I hope someone here can help me out.

The Issue:

When I attempt to run the npm run build command, I encounter the following error:

assets by status 364 bytes [cached] 1 asset
./src/index.js 224 bytes [built] [code generated] [1 error]

ERROR in ./src/index.js 7:12
Module parse failed: Unexpected token (7:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loadersers
| const rootElement = document.getElementById('root');
| const root = createRoot(rootElement);
> root.render(<App />);
|

webpack 5.93.0 compiled with 1 error in 357 ms

My Webpack Configuration:

Here’s my current Webpack configuration (webpack.config.js):

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const isDevelopment = process.env.NODE_ENV !== 'production';

module.exports = {
    mode: isDevelopment ? 'development' : 'production',
    devtool: isDevelopment ? 'eval-source-map' : 'source-map',
    entry: path.resolve(__dirname, 'src', 'index.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
    },
    resolve: {
        extensions: ['.js', '.jsx', 'json'],
    },
    devServer: {
        contentBase: path.resolve(__dirname, 'dist'),
        compress: true,
        port: 8080,
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'public', 'index.html'),
        }),
    ],
    module: {
        rules: [
            {
                test: /.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /.(css)$/,
                exclude: /node_modules/,
                use: ['style-loader', 'css-loader'],
            },
        ],
    },
};

My package.json:

{
  "name": "01-github-explorer",
  "version": "1.0.0",
  "main": "src/index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "cross-env NODE_ENV=production webpack",
    "dev": "webpack server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "@babel/preset-react": "^7.24.7",
    "react": "^18.3.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.24.8",
    "@babel/core": "^7.25.2",
    "@babel/polyfill": "^7.12.1",
    "@babel/preset-env": "^7.25.3",
    "babel-loader": "^9.1.3",
    "babel-polyfill": "^6.26.0",
    "cross-env": "^7.0.3",
    "css-loader": "^7.1.2",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.6.0",
    "style-loader": "^4.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.93.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^5.0.4"
  }
}

My Babel Configuration:

module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
  ],
};

What I’m Trying to Achieve:

I am trying to build my React application using Webpack. I have set up the Webpack configuration to handle JavaScript and CSS files, and I am using Babel to transpile modern JavaScript and React JSX syntax. However, I keep running into an error during the build process.