Fail to update state React [duplicate]

I’m following a tutorial to get Items from localStorage, this is the code:

export const CartProvider = ({ children }) => {
  const [cartItems, setCartItems] = useState([]);
  // Load cart items from local storage on component mount
  useEffect(() => {
    const storedCartItems = JSON.parse(localStorage.getItem("cartItems")) || [];
    console.log('Loaded cart items from localStorage:', storedCartItems);
    setCartItems(storedCartItems);
    console.log('Cart items:', cartItems);
  }, []);
  // Save cart items to local storage whenever cartItems state changes
  useEffect(() => {
    localStorage.setItem("cartItems", JSON.stringify(cartItems));
  }, [cartItems]);

So the problem is storedCartItems has the Items in it but the cartItems not get updated, it log out as blank[]. Please help.

Here is the console logging

JavaScript class not working on external file

(https://i.sstatic.net/wPIwfXY8.png)(https://i.sstatic.net/YFTflaOx.png)(https://i.sstatic.net/68IP9mBM.png)

I’m facing an error- if i create the class APIfeature in my tourcontroller.js file,it works just fine but whenever i try to take that class to another file and export then require it,it doesnt give me any data whenever i try to send a request from postman..

Tried to send request,but not getting any results back.

checkbox not rendering based on database value

I have a pop up box where one column has checkboxes, to see whether the the item has been published or not. I want the checkboxes to appear with its current state in the database while rendering. There is a field in backend called in_draft. (If its false , then the checkbox should be ticked, and vice versa). Only if a user check the blank checkbox, I want it to update to in_draft goes from True to False..I tried the following code,
but initially the checkboxes are appearing blank. When I click on any one
of them, it publised it, but after logging out and going to that pop up boxes,
all are blank…but in backend it is updated.

The code of foucs here is …..

<td class="text-center">
    <input type="checkbox" v-model="selectedReports" :value="report.id" 
                @change="handleCheckboxChange(report.id, $event.target.checked)"/>
    </td>

The async function is here:

async handleCheckboxChange(reportId, isChecked) {
      console.log("Checkbox changed:", { reportId, isChecked });
      this.isUpdating = true;
      try {
        if (isChecked) {
          console.log("Checkbox checked. Report ID:", reportId);
          
          // Check if the report is already in the selectedReports list
          if (!this.selectedReports.includes(reportId)) {
            
            this.selectedReports.push(reportId);
          } else {
            // console.log("Report already in selectedReports.");
          }

          // Publish the report if checked
          
          await this.$repository.studyReports.edit({ in_draft: false }, reportId);
          // console.log("Report published successfully.");
          this.$toast.success('Report published successfully.');
        } else {
          // console.log("Checkbox unchecked. Report ID:", reportId);
          
          // Remove the report from the selectedReports list
          if (this.selectedReports.includes(reportId)) {
            // console.log("Removing report from selectedReports.");
            this.selectedReports = this.selectedReports.filter(id => id !== reportId);
          } else {
            // console.log("Report not found in selectedReports.");
          }
        }
      } catch (error) {
        // console.error("Error in handleCheckboxChange:", error);
        this.$toast.error(`Error: ${error.response?.data?.error || error.message}`);
      } finally {
        // console.log("Resetting isUpdating flag.");
        this.isUpdating = false;
      }
    }

This is export part

export default {
  name: "ManageStudyReportsModal",
  components: { StudyReportEditForm, StudyReportForm },
  data() {
    return {
      addCollapse: null,
      editCollapse: null,
      isUpdating: false,
      studyreports: [],
      selectedReports: [], // IDs of the selected reports
      meta: {
        totalItems: 0,
        totalPages: 0,
        currentPage: 1,
        pageSize: 10,
      },
      report: null,
    };
  },

“jim.log()” is not a function

function extend<T, U>(first: T, second: U): T & U {
  let result = <T & U>Object.assign({}, first, second);
  return result;
}

class Person {
  constructor(public name: string) { }
}
interface Loggable {
  log(): void;
}
class ConsoleLogger implements Loggable {
  log() {
    console.log("11")
  }
}
var jim = extend(new Person("Jim"), new ConsoleLogger());
console.log(jim);

var n = jim.name;
jim.log();

Why does this code give an error saying ‘jim.log is not a function’? I checked and jim only has a name property. Why isn’t the log function assigned to the jim object?

How to prop Union Types in v-model of vue component :is?

I want to bind the value of apiRes to v-model, but typescript error occurred :

Here is the approximate code where I encountered the error.
How should I fix this?

Arguments of type { modelValue: Cars | undefined; } cannot be assigned to type NonNullable<(Partial<{}> & Omit<{ readonly modelValue?: Car | undefined; } & VNodeProps & AllowedComponentProps & ComponentCustomProps & Readonly<...> , never> & Record<...>) | (Partial<...> & ... 1 more ... & Record<...>)> & Parameters of Record<...>.
   
<template>
  <div>
    <component :is="component" v-model="apiRes" />
  </div>
</template>
<script lang="ts" setup>
import test1 from './test1.vue'
import test2 from './test2.vue'
import { computed, ref } from 'vue'

export interface Car {
  age: number
  name: string
}

export interface Car2 {
  door: string
  cvt: string
}

type Cars = Car | Car2

const component = computed(() => {
  const random = Math.random()
  return random > 0.5 ? test1 : test2
})


const apiRes = ref<Cars>()
</script>


//test1
<template>
  <div>{{ props }}</div>
</template>
<script setup lang="ts">
import type { Car } from './test.vue'

const props = defineModel<Car>()
</script>


//test2
<template>
  <div>{{ props }}</div>
</template>
<script setup lang="ts">
import type { Car2 } from './test.vue'

const props = defineModel<Car2>()
</script>

If I change it to the following, the error disappears, but this might not be the correct solution.

const apiRes = ref({} as Car)

How to detect the page is open by clicked “Open link in new tab”

I have home page, includes many anchor links to view movies.
As I need to track if user open the link from the home page, by right click “Open link a new tab”, or they directly open the link (like when they copy the link from somewhere then paste to browser).

For example, when view page X, how to know if this page is opened from the Home Page by click “Open link in new tab”.

Is there a way to do this by raw Javascript?
I would like to avoid using local storage, session storage or cookie.
Thanks

Issue with Horizontal Collision Detection in Game Development

I’m working on a game and having trouble with horizontal collision detection between the player and block objects. The collision seems to work fine when the player collides from below the block, but not when moving horizontally.

update() {
    // Apply gravity
    this.velocity.y += this.gravity;
    this.position.y += this.velocity.y;
    this.position.x += this.velocity.x;
    
    // Update hitbox position
    this.hitbox.position.x = this.position.x + 50;
    this.hitbox.position.y = this.position.y + 10;
    
    // Check for collisions
    this.checkForHorizontalCollisions();
    this.checkForVerticalCollisions();
    
    // Draw the player and hitbox for debugging
    ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
    ctx.fillRect(this.hitbox.position.x, this.hitbox.position.y, this.hitbox.width, this.hitbox.height);
    
    this.draw();
    
    // Reset velocity.x for movement logic
    this.velocity.x = 0;
    if (keys.a.pressed) {
        this.switchSprite("runLeft");
        this.velocity.x = -5;
    } else if (keys.d.pressed) {
        this.switchSprite("runRight");
        this.velocity.x = 5;
    } else {
        this.switchSprite(this.lastDirection === "left" ? "idleLeft" : "idleRight");
    }
}

checkForHorizontalCollisions() {
    for (let i = 0; i < this.collisionBlocks.length; i++) {
        const collisionBlock = this.collisionBlocks[i];

        // if a collision exists
        if (
            this.position.x <= collisionBlock.position.x + collisionBlock.width &&
            this.position.x + this.width >= collisionBlock.position.x &&
            this.position.y + this.height >= collisionBlock.position.y &&
            this.position.y <= collisionBlock.position.y + collisionBlock.height
        ) {
            // collision on x axis going to the left
            if (this.velocity.x < 0) {
                const offset = this.position.x - this.position.x;
                this.position.x = collisionBlock.position.x + collisionBlock.width - offset + 0.01;
                break;
            }

            if (this.velocity.x > 0) {
                const offset = this.position.x - this.position.x + this.width;
                this.position.x = collisionBlock.position.x - offset - 0.01;
                break;
            }
        }
    }
}

checkForVerticalCollisions() {
    for (let i = 0; i < this.collisionBlocks.length; i++) {
        const collisionBlock = this.collisionBlocks[i];

        // if a collision exists
        if (
            this.position.x <= collisionBlock.position.x + collisionBlock.width &&
            this.position.x + this.width >= collisionBlock.position.x &&
            this.position.y + this.height >= collisionBlock.position.y &&
            this.position.y <= collisionBlock.position.y + collisionBlock.height
        ) {
            if (this.velocity.y < 0) {
                this.velocity.y = 0;
                const offset = this.position.y - this.position.y;
                this.position.y = collisionBlock.position.y + collisionBlock.height - offset + 0.01;
                break;
            }

            if (this.velocity.y > 0) {
                this.velocity.y = 0;
                const offset = this.position.y - this.position.y + this.height;
                this.position.y = collisionBlock.position.y - offset - 0.01;
                break;
            }
        }
    }
}

I’ve also tried creating a hitbox for the player object, but it doesn’t seem to resolve the issue. The problem seems to occur specifically when moving horizontally. Any help would be greatly appreciated!

how to display data inside the alert box

I tried to enter a simple text word it appears then suddenly when I put the php inside the alert box it didn't show the data.

<script>

$(document).ready(function(){

$(“button”).click(function(){

alert(“($result[‘rightAns’] == ‘1’)”);

});

});

</script>

how can i display answer after i click the button

How to override the default value of an ENV variable in a JestJS Unit Test while testing an exported component?

I am working on a NextJS+React project and need to write a Unit Test using JestJS that depends on one ENV variable. The variables is named to SITE_BRAND and defaulted to brand value.

This is what the test looks like:

import {SignUp} from '@modules/sign-up'
import { render, screen } from '@testing-library/react'

describe('Sign Up page', () => {
    beforeEach( () => {
        jest.resetModules()
    })

    it('should render sign up form', () => {
        process.env.SITE_BRAND = 'brand1';

        render(<SignUp pageData={pageData} />)
        expect(screen.getByTestId('link-login')).toBeInTheDocument();
    })
})

The above expectation does fail if SITE_BRAND !== brand1 which is my issue because the ENV will not change after the component is imported which is my case.

I have Google this and found a few posts: 1, 2 and 3 and following the accepted answer on 2 I changed the test to this:

import { render, screen } from '@testing-library/react'

describe('Sign Up page', () => {
    beforeEach( () => {
        jest.resetModules()
    })

    it('should render sign up form', () => {
        process.env.SITE_BRAND = 'brand1';
        const SignUp = require('../Signup');

        render(<SignUp pageData={pageData} />)

        expect(screen.getByTestId('link-login')).toBeInTheDocument();
    })
})

but the test fails with the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

I also did Google the above issue but could not find anything helpful.

The component is exported as default:

const SignUp = () => { .... }

export default SignUp

How can I use a custom value for the ENV variable and test the component properly?

How to setup unit testing for React application using React Testing Library and Jest?

I have a simple react application that uses RTK Query and React Router. It makes an API call and it has 2 routes

  1. unauthorized
  2. welcome

I need help with testing setup and couple of sample tests using React Test Library and Jest.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <Routes>
        <Route path='/app' element={ <App />} />
      </Routes>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

App.js

import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';

import Unauthorized from './features/unauthorized/Unauthorized';
import NotFound from './features/notFound/NotFound';
import RequireAuth from './features/auth/RequireAuth';
import Welcome from './features/welcome/Welcome';

function App() {
  return (
    <Routes>
      <Route index path="unauthorized" element={ <Unauthorized />} />
      <Route path="*" element={<NotFound />} />
      <Route element={<RequireAuth groups={groups} />}>
         <Route path="welcome" element={<Welcome />} />
         <Route path="/" element={<Navigate to={welcome} />} />
      </Rout>
    </Routes>
  );
}

export default App;

Unauthorized.js

function Unauthorized(){
  return 'Unauthorized';
}

export default Unauthorized;

NotFound.js

function NotFound(){
  return 'Not Found!';
}

export default NotFound;

RequireAuth.js

import React from 'react';
import { Navigate, Outlet, useLocation } from 'react-router-dom';

function RequireAuth() {
  const location = useLocation();

  const isAuthorized = true;

  if (isAuthorized) {
    return <Outlet />;
  } else {
    return <Navigate to='unauthorized' state={{ from: location }} replace />
  }
}

export default RequireAuth;

Welcome.js

import React from 'react';
import { useGetWelcomeQuery } from './welcomeApi';

function Welcome() {
  const { data } = useGetWelcomeQuery();

  return (
    <div>
      <p>Welcome!</p>
      <h2>Messages</h2>
      {data.map((item) => (
        <p key={item.id}>{item.message}</p>
      ))}
    </div>
  );
}

export default Welcome;

store.js

import { configureStore } from '@reduxjs/toolkit'
import { welcomeApi } from "../features/welcome/welcomeApi";

export const store = configureStore({
  reducer: {
    [welcomeApi.reducerPath]: welcomeApi.reducer
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
  devTools: true
});

welcomeApi.js

export const welcomeApi = createApi({
  reducerPath: 'welcomeApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  endpoints: (builder) => ({
    getWelcome: builder.query({
      query: () => ({
         url: '/message'
      }),
    }),
    addWelcome: builder.mutation({
      query: (welcomeMessage) => ({
        url: '/message',
        method: 'POST',
        body: welcomeMessage,
      }),
    }),
    updateWelcome: builder.mutation({
      query: (welcomeMessage) => ({
        url: `message/${id}`,
        method: 'PUT',
        body: welcomeMessage
      }),
    }),
  }),
});

export const {
  useGetWelcomeQuery,
  useAddWelcomeMutation,
  useUpdateWelcomeMutation
} = welcomeApi;

How to detect a CSS class is active in or change CSS class name using Javascript [duplicate]

I have the following html codes:

    <li class="imagenav active">
      some codes go here
    </li>

Is there a way of checking if imagenav class is active or change CSS class using Javascript. for example:

    if imagenav is active {
      do some codes here ...
    }

Many thanks in advance.

Thank you for Barmar for advising how to check if a list has a class. However, in my case, I prefer to change CSS class using Javascript which makes it easier to manipulate my codes. So I have to add id into HTML codes. I want the left arrow to be active/disabled when the page is first loaded. Here are my fully working codes:

    <div id="active-leftarrow" class="imagenav">
      <script type='text/javascript'>
        document.getElementById('active-leftarrow').className = 'imagenav disabled';
      </script>
    </div>

Many thanks

Javascript not executing in Shopify theme customiser Custom Liquid sections

I’m fairly new to developing in the Shopify environment. Although the issue I’m currently encountering doesn’t seem particularly complicated, but it has me stumped.

The theme in use is Dawn, although I don’t think that should make any difference.

I have some JS I wanted to run on pages that use a particular template (product.warranty.json), which has been constructed in the theme customizer.

I added the JS using a “Custom Liquid” section in the template, via the customizer.

The original JS I tried adding was executing, but wasn’t identifying the target of the trigger, so I started adding in some console.log debug checks, yet nothing was appearing in the console.

I’ve now put together some debugging code to figure out what’s going on. But that’s not executing either. For instance, Debug script loaded doesn’t output to the Console.

What am I overlooking?

<script>
    console.log('Debug script loaded');

    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM fully loaded and parsed');

        function checkElementAvailability() {
            const formSelector = 'form[data-id="50018"]';
            const submitButtonSelector = "#globo-formbuilder-50018 > div > div > div > form > div.globo-formbuilder-wizard > div > div.gfb__footer.wizard__footer > button.action.next.submit.flat-button.wizard__submit";

            let startTime = Date.now();

            function logStatus() {
                const currentTime = Date.now();
                const elapsedTime = currentTime - startTime;

                const form = document.querySelector(formSelector);
                if (form) {
                    console.log(`[${elapsedTime}ms] Form with data-id 50018 found`);

                    const submitButton = form.querySelector(submitButtonSelector);
                    if (submitButton) {
                        console.log(`[${elapsedTime}ms] Submit button found`);
                    } else {
                        console.log(`[${elapsedTime}ms] Submit button not found yet`);
                    }
                } else {
                    console.log(`[${elapsedTime}ms] Form not found yet`);
                }

                setTimeout(logStatus, 50);
            }

            logStatus();
        }

        checkElementAvailability();
    });
</script>

How do I access string keys when using Typescript? [closed]

Let’s say I have the following model definition:

export interface formData {
    formSection: {},
    errors: formError[]
}

export interface formError {
    [key: string]: {
        'default'?: string
        '201'?: string
    }
}

and I receive a JSON like this:

{
  "formSection": {},
  "errors": {
    "firstName": {
      "default": "invalid first name",
      "201": "first name has invalid characters"
    }
  }
}

how can I access errors.firstName.default when TS does not know about the firstName key existence? If I do something like:

const myFunction = (param: formData) => {
    return (
        <>
            {param.errors.firstName.value}
        </>
    )
}

TS will complain saying firstName does not exist in the model, which is correct, but then how can I access that “dynamic” key?