Remove object from a list of arrays if field in object equals a certain value javascript

I have an array of objects and within those objects, I have another array. I want to filter the results by the checked value in the drilled-down array.

I have tried map, forEach, splice and I think I am missing something.

[
    {
        "id": 1,
        "parent": "Parent 1",
        "parents": [
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": false
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": false
            }
        ]
    },
    {
        "id": 1,
        "parent": "Parent 2",
        "parents": [
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": false
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": false
            }
        ]
    }
]

The results I am trying to get:

[
    {
        "id": 1,
        "parent": "Parent 1",
        "parents": [
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            }
        ]
    },
    {
        "id": 1,
        "parent": "Parent 2",
        "parents": [
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            },
            {
                "label": "New Item",
                "editable": true,
                "children": [],
                "checked": true
            }
        ]
    }
]

How do I add multiple input values into an array if some of the values are dynamically created?

I have an object that looks like this

    const [combat, setCombat] = useState({
        ac:'',
        proBonus:'',
        init:'',
        speed:'',
        atkPerRound:'',
        resistances:[]
    })

i also have a series of inputs that add their values to the respective key. one of the inputs is called resist and it has a button that makes a new input also called resist. its supposed to add the value of each input to the array in combat.resistances, but when i try to add a value to a dynamically created inputs i get this error
e.preventDefault is not a function TypeError: e.preventDefault is not a function
the function that adds the new input looks like this

    const handleAdd = (e) => {
        e.preventDefault()

        const newResistList = document.getElementById('newResistList')

        const newResist = document.createElement('input')
        newResist.type = 'text'
        newResist.placeholder = 'Resistance'
        newResist.name = 'resist'

        newResist.addEventListener('input', (e) => {
            handleChange(combat.resistances.length, {target: {value: e.target.value}})
        })

        newResistList.appendChild(newResist)
    }

and the function that adds the values to combat looks like this

    const handleChange = (e) => {
        e.preventDefault()

        if(e.target.name === 'resist'){
            setCombat({...combat, resistances: [e.target.value]})
        }else{
            setCombat({...combat, [e.target.name]: e.target.value})
        }
    }```


heres the `resist` input itself


        <p id='resistList'>
            <label htmlFor='resist'>Resistances</label>
            <input name='resist' type='text' onChange={handleChange} placeholder='Resistances'/>
            <span id='newResistList'></span>
            <button name='addButton' onClick={handleAdd}>Add Resistance</button>
        </p>




ive tried ending the `handleChange` function with `return false` and starting it with `stopPropogation`(ive heard that could work as a workaround to `preventDefault` not working) but it throws a `e.stopPropagation is not a function`. 

making it `return false` keeps it from reloading, but now my `handleChange` function throws a `Cannot read properties of undefined (reading 'name')` error.

so, i just logged `e.target` at the top of the `handleChange` function, and in new inputs its `undefined`, but when i log `newResist` at the bottom of the `handleAdd` function it logs properly.

When using the hook useState, it will be executed again

i have code for validation form in the next js V1

      setErrorF((errorF) => {
    if (
      errorF.FNameAndLName !== "" ||
      errorF.phoneNumber !== "" ||
      errorF.location1 !== "" ||
      errorF.gender !== "" ||
      errorF.methodeOfCourse !== ""
    ) {
      handleAlertinfo("خطاها را بررسی کنید.");
      return errorF;
    }
    return errorF;
  });

this code run for tow time but i want run for one time
i want use update errorF in the useState but that run for tow time how can solve that

How can I persist color changes to html elements?

In my attached code, I display a color picker, then I select a color, then I click the button “contact-info-btn” to change its background color to the selecetd color. However, the change is only good for that window. When refresh the window, it goes back to the old color. is there any way to make this change permanent?

<script>
document.querySelector('#contact-info-btn').addEventListener('click', (event) => {
            event.target.style.backgroundColor = document.querySelector("#color-picker").value
        });
<label for="color-picker">Color:</label>
    <input type="color" id="color-picker" />
    <form method="post" class="homepg-form" id="homepg-form" >
.
.
<button class="contact-info-btn" id="contact-info-btn" type="button" >İletişim bilgileri</button>        

Sequelize findAll is returning a array with a null object instead of an empty array

const getAmbassadors = async (req, res, next) => {
    try {
        const ambassadors = await Ambassador.findAll({ 
            
            include: [{model:Ticket,attributes:[]],
            attributes:{include:[[sequelize.fn("COUNT",sequelize.col("tickets.id")),"ticket_count",]]},
         });
        return res.status(200).send(dataResponse('success', { ambassadors }));
    } catch (error) {
        res.status(500).send('Internal Server Error');
        console.error(error);
    }
};

When there are no ambassador objects in the database i get the following output:

"ambassadors": [
            {
                "id": null,
                "name": null,
                "referral_code": null,
                "email": null,
                "institute": null,
                "ticket_count": 0
            }
        ]

i was expecting an empty array to be returned, but an array with a single object with null fields is being returned.
the problem gets fixed when this line is removed:

attributes:{include:[[sequelize.fn("COUNT",sequelize.col("tickets.id")),"ticket_count",]]},

but i need the ticket count. can someone point out how this can be fixed?

Is there a way to render the properties that start with ‘includes’? [closed]

enter image description hereI’m trying to render all properties that start with ‘includes’ from data.js to Includes.jsx. I’ve tried using startsWith(), but can’t seem to make it work.

[enter image description here](https://i.stack.imgur.com/f5Z8C.jpg)

I’ve tried iterating over the array using startsWith(includes), but I kept getting the error “startsWith is not a function’.

Using a page.on(‘response’) eventEmitter listener in Playwright automatic fixture

I am attempting to create a page.on(‘response’) event listener fixture that will be used across all my tests.

Currently, whenever there are certain events in my code base that will cause a div with a specific ID to appear in the UI.
I was able to get this to work by creating a separate method and including that in a beforeEach hook, however I was wondering if this would be possible to implement as an automatic fixture.

// helper.js

exports.test = base.test.extend({
  responseMacroErrorCheck: [async ({ page }) => {
    page.on('response', data => {
      if (data) {
        data.body().then(b => {
          let ioCheck = b.indexOf('example')
          if (b && ioCheck !== -1) {
            process.stdout.write(`Macro error detected on page (example)`)
            process.stdout.write(`${b.toString().substring(ioCheck - 500, ioCheck + 500)}`)
            throw new Error(`Macro error detected on page (example)n${b})}`)
          }
        })
      }
    })
    await use('responseMacroErrorCheck')
  }, { scope: 'test', auto: true }],
})

// error.spec.js

const scanUrlList = [
  'myUrl'
]

test.describe('Scan URL list for macro errors', () => {
  scanUrlList.forEach(ele => {
    test(ele, async ({ page }) => {
      await page.goto(`myUrl`)
    })
  })
})

The above method seems to make it so that responseMacroErrorCheck is not recognized by the code, however if I add the following code it runs just fine and as intended
// helper.js

export const responseMacroErrorCheck = async (page) => {
  page.on('response', data => {
    if (data) {
      data.body().then(b => {
        let ioCheck = b.indexOf('example')
        if (b && ioCheck !== -1) {
          process.stdout.write(`Macro error detected on page (example)`)
          process.stdout.write(`${b.toString().substring(ioCheck - 500, ioCheck + 500)}`)
          throw new Error(`Macro error detected on page (example)n${b})}`)
        }
      })
    }
  })
}

// error.spec.js

  test.beforeEach(async ({ page }) => {
    await h.responseMacroErrorCheck(page)
  })

Is there something I am missing in my automatic fixture? Or is it just that page emitted events are not recognizable in automatic fixtures?

Export Solid jsx components in index.js files?

I’ve tried all the suggestions for React that I’ve seen to no avail. They generally look like the following suggestions:

export { default as Footer } from '../components/Footer/Footer';

// or

import { Footer } from '../components/Footer.jsx';

export default [ Footer ]; // object notation has been suggested in place of array, as well

They typically all result in the same errors:

WARNING in ./src/App.jsx 22:29-35
export ‘Footer’ (imported as ‘Footer’) was not found in ‘./components’ (module has no exports)

ERROR in ./src/components/index.js 1:0-64
Module not found: Error: Can’t resolve ‘../components/Footer/Footer’ in ‘C:UserscsworenreposiFPMiFPMsrccomponents’

Has anyone gotten this to successfully work? It’s annoying with a half-dozen components, but we’re pushing for hundreds of nested components in the near future.

How to detect if any sound is played in any website, using JS?

Is there a way, using JS, to make any website display a message if a sound is played? For instance, if I’m on Facebook, when a notification sound is played, I want to intercept this sound and run any code I want via JS.

Something like the code below. I would open the website and inject the code below using dev tools.

window.onload = function() {
  if (soundPlayed) alert('A sound has played');
};

Why is my time not being formatted correctly and why are messages not saving when switching between channels?

As described in the question title, I have two problems here. I haven’t had much luck with solving them and I’m at the point where I decided to ask others after exhausting my resources and various attempts at refactoring.

The time keeps coming in a format like “Sun Jan 26 2025 13:59:05 GMT+0200 (Eastern European Standard Time)” and I can’t trace what makes that happen. It shouldn’t be the server, but I don’t understand what is doing this on my front-end either. My ‘formatTimeStamp’ function shows how I intend for the time to appear, depending on how much time has passed since the message.

I can submit messages to channels and they will appear in the messages panel, but they will not be there when I switch channels and then switch back. I have tried many suggestions from online and even asked AI to solve it, but I came across no solution that worked. I hope that somebody can have an answer to this and I would be ever so grateful. Thanks in advance to anybody who can solve this and don’t be afraid to ask for more context.

This is my server file:

const express = require('express');
const cors = require("cors");
const bodyParser = require('body-parser');

const app = express();
const port = 3001;
let corsOptions = {
    origin: "http://localhost:3000"
};

app.use(cors(corsOptions));

// In-memory database for channels and messages
let channels = [
  { id: 1, name: 'General', messages: [] },
  { id: 2, name: 'Random', messages: [] },
  { id: 3, name: 'News', messages: [] }
];

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

app.listen(port, () => {
  console.log(`nServer is running at http://localhost:${port}`);
});

// GET endpoint for querying channels
app.get('/channels', (req, res) => {
  res.json(channels.map(channel => ({ id: channel.id, name: channel.name })));
});

// GET endpoint for querying channel's messages
app.get('/messages/:channel', (req, res) => {
  const channelName = req.params.channel;
  const channel = channels.find(c => c.name === channelName);
  if (channel) {
    res.json(channel.messages);
  } else {
    res.status(404).json({ error: 'Channel not found' });
  }
});

// POST endpoint for submitting new messages to a channel
app.post('/:channel', (req, res) => {
  const channelName = req.params.channel;
  const channel = channels.find(c => c.name === channelName);
  if (channel) {
    const newMessage = { text: req.body.message, timestamp: new Date().toISOString() };
    channel.messages.push(newMessage);
    res.status(201).json(newMessage);
  } else {
    res.status(404).json({ error: 'Channel not found' });
  }
});

This is my front-end file:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = () => {
  const [channels, setChannels] = useState([]);
  const [selectedChannel, setSelectedChannel] = useState(null);
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');

  const baseURL = 'http://localhost:3001';

  useEffect(() => {
    // Fetch initial list of channels
    axios.get(`${baseURL}/channels`)
      .then(response => setChannels(response.data))
      .catch(error => console.error('Error fetching channels:', error));
  }, []);

  useEffect(() => {
    // Fetch messages when a channel is selected
    if (selectedChannel) {
      axios.get(`${baseURL}/messages/${selectedChannel}`)
        .then(response => setMessages(response.data))
        .catch(error => console.error(`Error fetching messages for ${selectedChannel}:`, error));
    }
  }, [selectedChannel]);

  const handleChannelSelect = (channel) => {
    setSelectedChannel(channel);
    setNewMessage('');
  };

  const formatTimestamp = (timestamp) => {
    const messageDate = new Date(timestamp);
    console.log(timestamp);
    const currentDate = new Date();

    let formattedTimestamp = '';

    if (messageDate.toDateString() === currentDate.toDateString()) {
      formattedTimestamp = messageDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } else {
      if (messageDate.getFullYear() !== currentDate.getFullYear()) {
        formattedTimestamp = messageDate.toLocaleTimeString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
      } else {
        if (Math.abs(currentDate - messageDate) < 7 * 24 * 60 * 60 * 1000) {
          formattedTimestamp = messageDate.toLocaleTimeString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        } else {
          formattedTimestamp = messageDate.toLocaleTimeString([], { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        }
      }
    }
    return formattedTimestamp;
  };

  const handleNewMessageSubmit = () => {
    if (newMessage) {
      axios.post(`${baseURL}/${selectedChannel}`, { message: newMessage })
        .then(response => setMessages([response.data, ...messages]))
        .catch(error => console.error('Error submitting message:', error));

      setNewMessage('');
    }
  };

  return (
    <div className="app">
      <div className="navigation-panel">
        <h2>Channels</h2>
        <ul>
          {channels.map(channel => (
            <li
              key={channel.id}
              onClick={() => handleChannelSelect(channel.name)}
              className={selectedChannel === channel.name ? 'selected' : ''}
            >
              {channel.name}
            </li>
          ))}
        </ul>
      </div>
      <div className="message-list-panel">
        <h2>Messages</h2>
        <ul>
          {messages.map((message, index) => (
            <li key={index}>
              {message.text}
              <span className="timestamp">{formatTimestamp(message.timestamp)}</span>
            </li>
          ))}
        </ul>
      </div>
      {selectedChannel && (
        <div className="editor-panel">
          <h2>Editor</h2>
          <textarea
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
          />
          <button onClick={handleNewMessageSubmit} disabled={!newMessage}>
            Submit
          </button>
        </div>
      )}
    </div>
  );
};

export default App;

Not sure if this matters, but for completion sake, here’s my styles too:

body {
  margin: 0;
  font-family: 'Roboto', sans-serif;
  background-color: #f5f5f5; /* Light gray background */
  color: #333; /* Dark text color */
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.app {
  display: flex;
  max-width: 800px;
  width: 100%;
  margin: 20px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.1);
}

.navigation-panel,
.message-list-panel,
.editor-panel {
  flex: 1;
  padding: 20px;
}

.navigation-panel {
  background-color: #007bff; /* Primary blue */
  color: white;
  border-top-left-radius: 12px;
  border-bottom-left-radius: 12px;
}

.navigation-panel h2 {
  color: white;
  font-size: 1.8rem; /* Larger font size for headers */
  margin-bottom: 15px;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  margin-bottom: 10px;
  padding: 15px;
  background-color: #e1e1e1; /* Light gray background */
  border-radius: 8px;
  transition: background-color 0.3s ease;
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
  color: #333; /* Dark text color */
  font-size: 1.2rem; /* Slightly larger font size */
}

li:hover {
  background-color: #d4d4d4; /* Slightly darker gray on hover */
}

.message-list-panel {
  background-color: #ffffff;
  border-right: 2px solid #dee2e6;
  border-left: 2px solid #dee2e6;
}

.message-list-panel h2 {
  color: #007bff;
  font-size: 1.8rem; /* Larger font size for headers */
  margin-bottom: 15px;
  border-bottom: 2px solid #dee2e6;
  padding-bottom: 10px;
}

ul li {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 15px;
  transition: background-color 0.3s ease;
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
  color: #333; /* Dark text color */
  font-size: 1.2rem; /* Slightly larger font size */
}

ul li:hover {
  background-color: #6c757d;
}

.editor-panel {
  background-color: #28a745; /* Green */
  color: white;
  border-top-right-radius: 12px;
  border-bottom-right-radius: 12px;
}

.editor-panel h2 {
  color: #218838;
  font-size: 1.8rem; /* Larger font size for headers */
  margin-bottom: 15px;
  border-bottom: 2px solid #dee2e6;
  padding-bottom: 10px;
}

textarea {
  width: calc(100% - 20px);
  height: 100px;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #28a745;
  border-radius: 5px;
  outline: none;
  resize: none;
  font-size: 1.2rem; /* Slightly larger font size */
  color: #333; /* Dark text color */
}

button {
  width: 100%;
  padding: 10px;
  cursor: pointer;
  background-color: #6c757d; /* Gray */
  color: white;
  border: none;
  border-radius: 5px;
  outline: none;
  transition: background-color 0.3s ease;
  font-size: 1.2rem; /* Slightly larger font size */
}

button:disabled {
  background-color: #cccccc; /* Light gray for disabled state */
  cursor: not-allowed;
}

.timestamp {
  position: absolute;
  display: flex;
  font-size: 0.8rem;
  color: #888; /* Timestamp color */
}

.selected {
  background-color: #6c757d; /* Highlight color for the selected channel */
  color: white;
}

@media (min-width: 768px) {
  .app {
    max-width: 1200px;
  }
}

Try to Display Number of Choice Selected at Any Time on Django Form MultipleChoiceField

I am building an application for a real estate project. As part of this, I have “listing” items in my database that I filter and display on my SearchTool.html page. One of the search functions includes a button that says “Select Property Type” on it. When you click the button, a small popup displays all of the multiple-choice field options from my Django form. I want the button to show how many choices are selected so that if the popup is closed you don’t have to reopen it to know how many are active. Currently, it seems to mostly work. The popup works great. But, the counter has some problems. When I select exactly on the checkbox then the counter works fine but when I select the text to toggle the choice the counter doesn’t catch it. When I click on the text like this, the backend still registers it because it sorts my listings correctly. So, there is an issue with the html/js not registering when I select the text vs the box itself.

I am new to Django so please let me know if this question has been answered or if I am missing something obvious.

Here is some of my relevant code, let me know if I need to include anything else:

SearchTool.html:

<div class="form-group row" style="margin-bottom: 1%;">
                        <label for="id_Property_type" class="col-sm-6 col-form-label text-end text-uppercase fw-bold" style="font-size: 1.75rem;">Property Type:</label>
                        <div class="col-sm-6">
                            <!-- Add a button to trigger the popup -->
                            <button type="button" onclick="showPropertyTypes()" class="btn btn-primary">
                                Select Property Type
                                <span id="propertyTypeCounter" class="badge bg-secondary">All</span>
                            </button>
                    
                            <!-- Hidden div to display property types when the button is clicked -->
                            <div id="propertyTypePopup" class="popup" style="display: none;">
                                {% for choice in form.Property_type %}
                                    <div id="propertyTypePopupA">
                                        <button type="button" onclick="selectPropertyType(this, event);">{{ choice }}</button>
                                    </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>

JS (located below the above html right after the ):

 <script>
        var popup = document.getElementById("propertyTypePopup");
        var counter = document.getElementById("propertyTypeCounter");
    
        function showPropertyTypes() {
            if (popup.style.display === "block") {
                popup.style.display = "none";
            } else {
                popup.style.display = "block";
                popup.style.top = "50px"; // Adjust as needed
                popup.style.left = "0";   // Adjust as needed
            }
        }
    
        window.onclick = function (event) {
            if (!event.target.matches('.btn') && !event.target.matches('.popup') && !event.target.closest('.popup')) {
                popup.style.display = "none";
            }
        };
    
        popup.onmouseleave = function () {
            popup.style.display = "none";
        };
    
        function selectPropertyType(button) {
            // Ensure that the 'button' variable refers to the correct button element
            var selectedButton = button.tagName === 'BUTTON' ? button : button.closest('button');
            selectedButton.classList.toggle('selected');
            updateCounter();
        }
    
        function updateCounter() {
            var selectedCount = document.querySelectorAll('#propertyTypePopupA button.selected').length;
            counter.innerText = selectedCount;
        }
    </script>

Relevant part of Forms.py:

 Property_type = forms.MultipleChoiceField(choices=Property_type, required=False, widget=forms.CheckboxSelectMultiple)

React Leaflet Material UI divIcon not styled

In React Leaflet, I am trying to use divIcon to render a custom Material UI marker that takes in a background color prop. However, when the marker is used in leaflet, the background style is not applied.

Below is the code for the project:

Codesandbox: https://codesandbox.io/p/sandbox/leaflet-mui-icon-forked-g23sc3?file=%2Fsrc%2FApp.js

Demo.js

import * as React from "react";
import Button from "@mui/material/Button";
import LeafletMarker from "./LeafletMarker";
import { Marker, Popup, MapContainer, TileLayer } from "react-leaflet";
import ReactDOMServer from "react-dom/server";
import "leaflet/dist/leaflet.css";
import Box from "@mui/material/Box";
import L from "leaflet";

export default function Demo() {
  return (
    <div>
      <LeafletMarker bgcolor={"green"} />
      <MapContainer
        center={[51.505, -0.09]}
        zoom={13}
        scrollWheelZoom={true}
        style={{ width: "100%", height: "100vh" }}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker
          draggable={true}
          position={[51.505, -0.09]}
          icon={L.divIcon({
            className: "",
            html: ReactDOMServer.renderToString(
              <LeafletMarker bgcolor={"red"} />
            ),
          })}
        />
      </MapContainer>
    </div>
  );
}

LeafletMarker.js

import Box from "@mui/material/Box";
import { createSvgIcon } from "@mui/material/utils";

const HomeIcon = createSvgIcon(
  <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />,
  "Home"
);

function LeafletMarker({ bgcolor }) {
  return (
    <Box
      sx={{
        width: "50px",
        height: "50px",
        borderRadius: 5,
      }}
      style={{ backgroundColor: bgcolor }}
    >
      <HomeIcon />
    </Box>
  );
}
export default LeafletMarker;

I have been able to get the background color to show by adding style={{ backgroundColor: bgcolor }} in LeafletMarker however I would prefer to get it working using the sx property if possible.

apiKey returning undefined using browserify & dotenv

Hoping someone might be able to help me to resolve the below.

I am trying to utilise .env to store my API key. I have tried several methods but have been unable to return/ use my API key as of yet.

So far I have tried the following:

  1. Using dotnev
    I could console.log the API key in the terminal but then hit other challenges when opening my code in a browser. I could not seem to resolve this using square brackets or similar
    Screenshot of error

In HTML
`<script src=”./node_modules/requirejs/require.js”

`

In my JS file
require("dotenv").config(); const apiKey = process.env.API_KEY; console.log(apiKey);

In .env
API_KEY = "123ABC"

  1. Adding browserify to bundle

In HTML
<script defer src="./bundle.js"></script>

In my JS file
require("dotenv").config(); const apiKey = process.env.API_KEY; console.log(apiKey);

In .env
API_KEY = "123ABC"

I’m then running browserify index.js > bundle.js in the VS Code integrated terminal.

The console.log(apiKey) results in undefined.

Would anyone be able to suggest any workarounds? I have seen webpack in some solutions but for this project am keen not to use webpack.

For clarity, I am copying the path of my index.html and pasting into the browser, not using the VS Code Live Server add on (this caused other issues around require not being defined)

Thanks so much!

react-scripts don’t work after src/ directory renamed

I renamed src/ to frontend/ and after this I have it searching in old folder src/:

$ npm run build

> [email protected] build
> react-scripts build

Could not find a required file.
  Name: index.js
  Searched in: /home/porton/Projects/passport_client_dfinity/src

despite I have created webpack.config.js:

const path = require('path');

// webpack.config.js
module.exports = {
    entry: './frontend/index.js',
    resolve: {
        modules: [path.resolve(__dirname, 'frontend'), 'node_modules'],
    },
};

Here is package.json:

{
  "name": "passport_client_dfinity",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@dfinity/agent": "^0.20.2",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.18.70",
    "@types/react": "^18.2.47",
    "@types/react-dom": "^18.2.18",
    "@web3-onboard/core": "^2.21.2",
    "@web3-onboard/injected-wallets": "^2.10.11",
    "@web3-onboard/react": "^2.8.13",
    "@web3-onboard/walletconnect": "^2.5.3",
    "bootstrap": "^5.3.2",
    "ethers": "^6.10.0",
    "react": "^18.2.0",
    "react-bootstrap": "^2.9.2",
    "react-dom": "^18.2.0",
    "react-spinners": "^0.13.8",
    "typescript": "^4.9.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "backend": "dfx deploy backend && env -i scripts/read-env.sh",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "sources": "mops sources"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "browser": {
    "fs": false,
    "os": false,
    "path": false
  },
  "devDependencies": {
    "react-scripts": "^5.0.1"
  }
}

I have a nested object stored in sessionStorage but returning string values after parsing

I want to return a complete object after parsing my object without repeatedly having to parse each level. Is this possible, have i stored my data incorrectly using redux-persist?

So, I have a login form that sends credentials over to my server to bring data such as accesstoken. This data is sent to sessions automatically via redux persist.

Everytime i want to access this data i need to parse the session storage and then parse again to access the data.

Heres my parsed code:

const TOKEN = JSON.parse(sessionStorage.getItem('persist:root'))

console.log(TOKEN)

result
{user: '{"currentUser":null,"isFetching":false,"error":false,"message":null}', users: '{"users":[],"isFetching":false,"error":false,"message":null}', selectUser: '{"selectUser":[],"isFetching":false,"error":false,"message":null}', product: '{"products":[],"isFetching":false,"error":false}', _persist: '{"version":1,"rehydrated":true}'}

Each nested object value is returned as a string and not an object. Meaning ill have to parse the next portion everytime i want to go deeper into the object or my objects grow.

Is there a work around, a way to have sessionStorage parsed once and returning a completely parsed nested object or is the error the way the object is initially stored.

Is redux to blame in how the object is initially stored. Here is my redux store file displaying reducers:

import userReducer from "./userRedux";
import productReducer from "./productRedux";
import usersReducer from "./usersRedux";
import selectUserReducer from "./selectUserRedux";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storageSession from "reduxjs-toolkit-persist/lib/storage/session"
//import storageSession from "redux-persist/lib/storage/session";

const persistConfig = {
  key: "root",
  version: 1,
  storage: storageSession,
};

const rootReducer = combineReducers({
  user: userReducer,
  users: usersReducer,
  selectUser: selectUserReducer,
  product: productReducer,
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});

export let persistor = persistStore(store);

Heres my user reducer:

mport { createSlice } from '@reduxjs/toolkit';

const initialState = {
        currentUser: null,
        isFetching: false,
        error: false,
        message: null,
    }

const userSlice = createSlice({
    name:"loggedUser",
    initialState,
    reducers: {
        loginStart: (state) =>{
            state.isFetching= true
        },
        loginSuccess: (state, action) =>{
            state.isFetching= false;
            state.currentUser= action.payload;

        },
        loginFailure: (state, action) => {
            state.isFetching= false;
            state.error= true; 
            state.message= action.payload;
        },
    },
});

export const { loginStart, loginSuccess, loginFailure  } = userSlice.actions;
export default userSlice.reducer;