Why is this React state variable not accepting new values?

I have state variables in a React context

export const FormProvider = ({ children }) => {
  const dispatch = useDispatch();
  const loadedForm = useSelector((state) => state.forms.newForm);
  const [title, setTitle] = useState(loadedForm.title);
  const [description, setDescription] = useState(loadedForm.description);
  const [questions, setQuestions] = useState(loadedForm.questions);
  const [headerNotes, setHeaderNotes] = useState(loadedForm.headerNotes);
  const [footerNotes, setFooterNotes] = useState(loadedForm.footerNotes);

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

  useEffect(() => {
    dispatch(
      updateNewForm({
        title,
        description,
        questions,
        headerNotes,
        footerNotes,
      })
    );
  }, [title, description, questions, headerNotes, footerNotes, dispatch]);

  return (
    <FormContext.Provider
      value={{
        title,
        setTitle,
        description,
        setDescription,
        questions,
        setQuestions,
        headerNotes,
        setHeaderNotes,
        footerNotes,
        setFooterNotes,
      }}
    >
      {children}
    </FormContext.Provider>
  );
};

All variables are updating correctly when I use the setValue except setQuestions

When I use setQuestions, it will update if I change a property of one of the questions, such as question.id. However, it does not update when I set the value to a different array.

I’m trying to delete a question using

const { questions, setQuestions } = useContext(FormContext);

function removeQuestion() {
    let newQuestions = [...questions];
    newQuestions = newQuestions.filter((q) => q.id !== question.id);
    setQuestions(newQuestions);
  }

But questions is not updating

Other functions are working though, like

function changeText(text) {
    const newQuestions = [...questions];
    newQuestions.find((q) => q.id === question.id).text = text;
    setQuestions(newQuestions);
  }

Any assistance is greatly appreciated!

I created another function in the context

const qs = (questions) => {
    console.log("questions", questions);
    setQuestions(questions);
  };

When I use this inside the removeQuestion function, it does print the correct array with the question removed, but questions is not updating to the new value.

Filter array of objects with multiple conditions

I have an array of objects that looks like this:

const pets = [
    {name: "Dog", tags: "ground, pet, active"},
    {name: "Cat", tags: "ground, pet, relaxed"},
    {name: "Fish", tags: "water, pet, exotic"},
] 

I want to filter out the array based on the tags key from a given keyword:

const search = "ground"
const result = pets.filter((pet) => pet.tags.includes(search)) 

It outputs this:

[
  { name: 'Dog', tags: 'ground, pet, active' },
  { name: 'Cat', tags: 'ground, pet, relaxed' }
]

What if I want to filter out the pets array with multiple keywords on the tags like this:

const search = ["ground", "active"]

In theory, only the { name: 'Dog', tags: 'ground, pet, active' } should be found given the two keywords.

Any ideas how can I achieve something like this?

How sum values of a table with decimals

I have a project in HTML and JS whit a table and input


<input type="text" id="suma">


<table id="myTable">
<tbody>
<tr>
<td>N</td>
<td>NOMBRE</td>
<td>MONTO</td>
</tr>
<tr>
<td>1</td>
<td>Alba</td>
<td>1.200,00</td>
</tr>
<tr>
<td>2</td>
<td>Andrea</td>
<td>1.200,00</td>
</tr>
<tr>
<td>3</td>
<td>Jose</td>
<td>1.200,00</td>
</tr>
</tbody>
</table>


function total(){
    var table = document.getElementById('myTable');
    let total = 0
    for(let i = 1; i<table.rows.length; i++){
        total+=Number(table.rows[i].cells[2].innerText)
    }
    const totalInput = document.getElementById('suma')
    totalInput.value=Intl.NumberFormat('en-EN').format(total)

}

The script can calculate the total of the MONTO field in the input, but the result is NaN because the values have decimals and thousand separator. The question is, How i can make for the script sum includes decimals and thousands separator? that is to say, with this format: 1.200,00

Thank you.

Can php development is good in 2024? [closed]

I am a new in development field but I am little bit confuse about choosing any programming language. I want to become a web developer but I am confuse in python (django), C# (ASP.NET), JavaScript (Node.js) and php. I need to help for choosing field.

I tried any one in little bit.

Picker.js et date in Javacript

Trying to create a picker in Javascript where I can get the date out of (and the time, eventually). I have made it in jsfiddle: https://jsfiddle.net/ariley/ej37qv5w/18/

Here’s the JS part of the code:

   const picker = new Picker(document.querySelector('.js-inline-picker'), {
  controls: true,
  inline: true,
increment: {
    year: 1,
    month: 1,
    day: 1,
    hour: 1,
    minute: 15,
  },
    format: 'YYYY/MM/DD',
            date: new Date(), // default to today's date
            text: {
                title: 'Pick a date',
            },
});



        // Listen for when a date is selected
        picker.getDate('pick', function(date) {
            // Date is picked. Let's store it!
            const selectedDate = date.format('YYYY/MM/DD');
            console.log('Selected Date:', selectedDate); // Or do whatever you wish with it
            
            // Example: Storing in localStorage
            localStorage.setItem('selectedDate', selectedDate);
        });

I’m unable to get the date, but there are no errors. What am I doing wrong?

Thank you!

Making Prism JS to work in Rails 7 with Import Maps

I would like to use Prism in my Rails 7 project to highlight code in specific pages.

To make that:

  1. I downloaded the Development version of Prism for Markup + HTML + …, CSS, C-like, and JavaScript languages, and with all the available plugins.
  2. I imported the Prism library in Rails 7 by following the Path 2: Download css and js files into your vendor folder blog post.

Now, in my Rails project I’ve these files:

project
> vendor
  > javascript
    > prism.js
  > stylesheet
    > prism.css

I also changed relevant files by adding Prism-related references:

# config/importmap.rb
pin 'prism', to: 'prism.js'

# app/javascript/application.js
import 'prism'

# app/assets/stylesheets/application.css.scss
@import 'stylesheet/prism';

To verify code highlighting, in a my test.html.erb template file I added the following:

<pre><code class="language-css line-numbers">
  p {
    color: red;
    text-align: center;
  }
</code></pre>

But when I render that page then in the browser console I get the error Uncaught TypeError: Prism.languages.css.selector.inside is undefined.

How to solve the problem?

.env.local variables not being accessed (undefined) in Next.js

I am trying to access my environment variables in my application made with Next.js.

From the Next.js docs. I need to put the environment variables in a .env.local file and access them with process.env.<ENV_VARIABLE>. I have done all this, but it is still returning undefined.

Relevant file paths:

root/.env.local

root/db/index.ts

.env.local:

ENV_VAR=test
NEXT_PUBLIC_ENV_VAR=publicTest

db/index.ts:

console.log(process.env.ENV_VAR)
console.log(process.env.NEXT_PUBLIC_ENV_VAR)

In every thread I’ve come across on Stack Overflow so far the accepted answer is to use NEXT_PUBLIC_ for the environment variable, but this had no effect. The index.ts file returns undefined for both variables.

From another thread I have added reactStrictMode: true to nextConfig in next.config.cjs, but that also had no effect.

I had dotenv installed, but after looking at aanother thread and one on GitHub, I uninstalled dotenv twice, once with npm uninstall dotenv and again with npm r dotenv. These commands also had no effect.

I use ts-node --esm db/index.ts to run the index.ts file.

renderToString “You’re importing a component that imports react-dom/server.”

I was trying to use the renderToString function as some libraries such as leaflet require it to make custom markers. Below is a simple example that recreates the error in a fresh React project:

import { renderToString } from 'react-dom/server';

const html = renderToString(<h2>some content</h2>);


export default function Home() {
  return (
    <main >
      <div >
        <h1>My React App</h1>
      </div>
    </main>
  );
}

Running the code gives the following error:

    ./app/page.js
Error: 
  × You're importing a component that imports react-dom/server. To fix it, render or return the content directly as a Server Component instead for perf and security.
  │ Learn more: https://nextjs.org/docs/getting-started/react-essentials
   ╭─[D:Reactmy-appapppage.js:1:1]
 1 │ import { renderToString } from 'react-dom/server';
   · ──────────────────────────────────────────────────
 2 │ 
 3 │ const html = renderToString(<h2>some content</h2>);
   ╰────

is there anyway to use renderToString?

Angular 17: ‘No provider for _HttpClient!’ Error in Standalone Component with ApiService

I am working on an Angular 17 application that incorporates the Spotify API using the new standalone component feature and am encountering an issue when trying to inject the HttpClient into a service. Despite following the Angular documentation on how to properly import and provide the HttpClientModule, I keep receiving the following error:

Error:

ERROR Error [NullInjectorError]: R3InjectorError(Standalone[_HomeComponent])[_ApiService -> _ApiService -> _HttpClient -> _HttpClient]: 
  NullInjectorError: No provider for _HttpClient!
    at NullInjector.get ...

Api Service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private baseUrl = 'http://localhost:8888';

  constructor(private http: HttpClient) { }

  login(): Observable<any> {
    return this.http.get(`${this.baseUrl}/login`);
  }

  checkLoginStatus(): Observable<boolean> {
    return new Observable<boolean>(observer => {
      observer.next(true); // Dummy implementation
      observer.complete();
    });
  }
}

Main.ts:

import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { provideHttpClient } from '@angular/common/http';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient()
  ],
}).catch((err) => console.error(err));

Home Component:

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../services/api/api.service';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [
    CommonModule,
    HttpClientModule
  ],
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  constructor(private apiService: ApiService) { }

  ngOnInit(): void {
    // Implementation omitted for brevity
  }
}

I’ve been working to resolve a “No provider for _HttpClient!” error in my Angular 16 application, following several steps aligned with Angular’s documentation. Initially, I ensured that my components were correctly marked as standalone (standalone: true), which resolved an earlier issue. Using Angular’s provideHttpClient documentation, I adjusted the bootstrapApplication configuration in main.ts, including the correct use of provideHttpClient() to globally provide HttpClient. Despite these adjustments and experimenting with different import and provide strategies for HttpClientModule, the injector error persists. I expected these efforts, especially following the official guidance and adjusting the bootstrap configuration, to make HttpClient available for injection throughout my application. The ongoing issue suggests a possible misunderstanding or oversight in configuring dependency injection or component setup in the context of Angular’s new standalone component features.

https://angular.dev/guide/http/setup#providing-httpclient-through-dependency-injection

Is there a way to avoid Lity library fires when dragging an image that use Lity?

I have a draggable slider of images. These images have Lity library implemented which is used to open a lightbox when the user click on every image.
The problem is that I’m unable to drag the images to navigate through the slides because Lity triggers every time I release the click after draggin images.
I would like to know if there is a way to avoid that. I need Lity to trigger only when I click the image, but not when I drag it.

This is the javascript library I refer.
I also left this issue on Github to see if someone can help me there.

Thank you!

This is what I have. But nothing much relevant here. Only a foreach to print the images and the data-lity attribute on each one.

<div class="small-slider__slider">
<?php
foreach ( $args['screenshots'] as $screenshot ) : ?>
    <article class="small-slider__item">
        <div class="post__image">
            <?php if ( ! empty( $src_low_res ) || ! empty( $src_high_res ) ) : ?>
                <a data-lity href="<?php echo $src_high_res; ?>">
                    <img loading="lazy" src="<?php echo $src_low_res; ?>" alt="<?php echo $alt; ?>">
                </a>
            <?php endif; ?>
        </div>
    </article>
    <?php
endforeach;
?>
</div>

Note: the Lity js library is working ok, except for the described problem and the slider js library is also working well, the dragging functionality works perfect. And I don’t have console erros.

If something is not clear, please leave me a comment with your question.
Thanks!!

Iterating through a JSON data in ReactJS, counting items and filtering by date in the data object

In reactJS, for the json data below, I want to generate an Array of the total count of “type” and an array of unique day of the month of November:
Output of total count of “type” for November should be [6, 2] based on two different dates in November, 19th and 20th respectively, while the output of unique day in November should be [19, 20].

{
  "data": [
    {
      "id": "1",
      "message": "successful",
      "data": [
        {
          "type": "abcdef"
        },
        {
          "type": "abcdef"
        }
      ],
      "date": "19/11/2023"
    },
    {
      "id": "2",
      "message": "successful",
      "data": [
        {
          "type": "abcdef"
        },
        {
          "type": "abcdef"
        }
      ],
      "date": "19/11/2023"
    },
    {
      "id": "3",
      "message": "successful",
      "data": [
        {
          "type": "abcdef"
        },
        {
          "type": "abcdef"
        }
      ],
      "date": "19/11/2023"
    },
    {
      "id": "4",
      "message": "successful",
      "data": [
        {
          "type": "abcdef"
        },
        {
          "type": "abcdef"
        }
      ],
      "date": "20/11/2023"
    },
    {
      "id": "5",
      "message": "successful",
      "data": [
        {
          "type": "abcdef"
        },
        {
          "type": "abcdef"
        }
      ],
      "date": "24/12/2023"
    },
    {
      "id": "6",
      "message": "successful",
      "data": [
        {
          "type": "abcdef"
        },
        {
          "type": "abcdef"
        }
      ],
      "date": "07/12/2023"
    },
    {
      "id": "7",
      "message": "successful",
      "data": [
        {
          "type": "abcdef"
        },
        {
          "type": "abcdef"
        }
      ],
      "date": "15/01/2024"
    }
  ]
}