ContextAPI not working in NextJS as expected [duplicate]

I have a school project were I need to use NextJS, in certain point I needed to use ContextAPI to manage some things as inputs, auths and decorative elements with buttons but every single use I cannot make it work, frustrated I made an example with basic elements following a tutorial but it didn’t work, if you have suggestions, recommendations or solutions please make me know… i’m still a little frog in this.

Here’s the example with basic elements:

Panel:

'use client';

import React, { useState } from 'react';

import './panel.css';

import Cajauno from './components/cajas';
import Cajados from './components/cajas2';

import { CambiarPanelCX } from './contexts/cambiarpanel';

function Panel() {
    const [showCaja, setShowCaja] = useState(false);
    return (
        <>
            <div class="displaycajas">
                <CambiarPanelCX.Provider value={{ setShowCaja }}>
                    {showCaja ? <Cajados /> : <Cajauno />}
                </CambiarPanelCX.Provider>
            </div>
        </>
    );
}

export default Panel;

Boxes:

import './cajas.css';


function Cajados() {
    return (
        <>
        <div class="cj2">
            Hola2
        </div>
        </>
    );
}

export default Cajados;
import './cajas.css';

function Cajauno() {
    return (
        <>
        <div class="cj1">
            Hola1
        </div>
        </>
    );
}

export default Cajauno;

Panel w/button:

'use client';

import React, { useContext } from 'react';

import './panel.css';

import { CambiarPanelCX } from './contexts/cambiarpanel';

function Panelbtn() {
    const { setShowCaja } = useContext(CambiarPanelCX);

    return (

        <>
            <div class="displaycajabtn">
                <button 
                    onClick={setShowCaja}
                >
                    Click me
                </button>
            </div>
        </>
    );
}

export default Panelbtn;

Context:

import  { createContext } from 'react';

export const CambiarPanelCX = createContext({});

Main page:

import Head from 'next/head';

import './deco.css';
//Components
import Panel from '../../panel';
import Panelbtn from '@/src/panelbtn';

export default function PrincipalP() {
  return (
    <>
      <Head>
        <title>Nose</title>
      </Head>
      <Panel />
      <Panelbtn />
    </>
  );
}

Convert vue3+vite project to SSR

I have a project built with vue js 3 + vite
How can i make it ssr
In the simplest way possible, since I don’t have much time
To become better for SEO

I tried more than one educational content, but the methods were difficult or incomprehensible. Can someone help me with this topic?

I want to clear local storage when i close either all my tabs(on last tab close) or on browser close

can you all suggest some approaches by which i can clear local storage on last tab close and on browser close..

can you all suggest some other approaches by which i can clear local storage on last tab close and on browser close.

I used local storage and session storage to maintain a array in localstorage of sessions open and close and when the array is empty i clear Local Storage. but it is not working on the condition when user shutdown its pc without closing its browser or tab.

my code…

@HostListener('window:load', ['$event'])
  loadHandler(event: Event) {
    let hash = 'tab_' + formatDate(new Date(), 'yyyy/MM/dd-hh:mm:ss:ms', 'en');
    sessionStorage.setItem('TabHash', hash);
    let tabs = JSON.parse(localStorage.getItem('TabsOpen')) || [];
    console.log(tabs);
    tabs.push(hash);
    localStorage.setItem('TabsOpen', JSON.stringify(tabs));
  }
 
  @HostListener('window:unload', ['$event'])
  beforeunloadHandler(event: Event) {
    let hash = sessionStorage.getItem('TabHash');
    let tabs = JSON.parse(localStorage.getItem('TabsOpen')) || [];
    tabs.pop();
    localStorage.setItem('TabsOpen', JSON.stringify(tabs));
 
    setTimeout(() => {
      let left_tabs_Open = localStorage.getItem('TabsOpen');
      if (left_tabs_Open == '[]') {
        window.localStorage.clear();
      }
    });
  }

Problem with fetch /api/register getting the error http://localhost:3000/api/register 404 (Not Found)

I have tried everything I am just confused about what I am doing wrong because I redid all of the code completely and still ran into the error. Is there more that I have to do for fetch besides making a file directory to /api/register?

I’m new to posting questions on stack so it’s not letting me put my code here but I am free to answer any questions because I am so lost.

"use client";
import {signIn} from "next-auth/react";
import Image from "next/image";
import Link from "next/link";
import {useState} from "react";

export default function RegisterPage() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [creatingUser, setCreatingUser] = useState(false);
  const [userCreated, setUserCreated] = useState(false);
  const [error, setError] = useState(false);
  async function handleFormSubmit(ev) {
    ev.preventDefault();
    setCreatingUser(true);
    setError(false);
    setUserCreated(false);
    const response = await fetch('/src/api/register', { 
      method: 'POST',
      body: JSON.stringify({email, password}),
      headers: {'Content-Type': 'application/json'},
    });
    if (response.ok) {
      setUserCreated(true);
    }
    else {
      setError(true);
    }
    setCreatingUser(false);
  }

How to see if focus on file picker dialogue in JavaScript

I have a table and each row has one or more user inputs with a focusout event listener attached, that calls a function:

function inputFocusOut(event, el) {
     let row = el.closest('tr');
     let curFocus = event.relatedTarget;
     let moveOn = true;
     
     if(focus was on dynamically added row) {
          // I have another way of handling these
          moveOn = false;
     } else if(curFocus) {
          // Check if in same row
          if(in same row) {
               moveOn = false;
          }
     } else if(el.nodeName === 'INPUT' && el.type === 'file') {
          // If focus on file picker, moveOn = false;
     }

     if(moveOn) {
          // Check if values changed and do more stuff if anything did change
     }
}

The function works great for everything except input[type='file']. When you click to upload a file, the focus is on the file picker dialogue, so the input loses focus, triggering the function.

Is it possible to know when focus is on the file browser window, in which case I don’t want to continue with the rest of the logic? The event.relatedTarget is undefined when the file picker is open, so I’m not sure what I would check.

I found this question, but the answer talks about putting focus on the input and blurring it, which I’m already doing (albeit with focuout instead of blur). Haven’t been able to find anything helpful, which could mean I’m not use the best search terms.

Any help in JavaScriptor jQuery would be appreciated.

how to pass the query result in view.py to Bootstrap-table

i use pymysql to get data from my database

conn = pymysql.connect(
        host='localhost',
        user='root',
        password='xxxxxxxxxx',
        database='TCR',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor,
    )
cur = conn.cursor()
result = cur.excute('SELECT * FROM TCR')
data = cur.fetchall()

Then i return ‘data’ to my HTML file

in HTML file i use Bootstrap-tabel to display my table. i notice that js part needs a .json file to fetch the data.
such as:

$('#table').bootstrapTable({
  url: 'data1.json',
  columns: [{
    field: 'id',
    title: 'Item ID'
  }, {
    field: 'name',
    title: 'Item Name'
  }, {
    field: 'price',
    title: 'Item Price'
  }]
})

but i don`t want to use .json, i want to use the variable ‘data’ in js. How do I convert data to a form acceptable to bootstrap-table?

i tried this

<div id="data-container" data-query-results = {{ data }} ></div>


<div id="reportTableDiv" >
        <table id="reportTable"></table>
    </div>
    <script type="text/javascript">
    text  = document.getElementById('data-container').getAttribute('data-query-results');
    console.log(text)
    var datas  = JSON.parse(text);

but i got an error when i use JSON.parase()

Uncaught SyntaxError: Expected property name or ‘}’ in JSON at position 2 (line 1 column 3)
at JSON.parse ()

Is there an easier way to achieve my purpose?

Forbidden (CSRF cookie not set) with cookie being sent from react axios to django backend

Building simple user authentication with React and Django but have only got register coded so far. I have tried getting this to work for hours and am getting very frustrated.The react side is built and the register page is being run from the django port 8000.

The development server is getting the cookie and setting it perfectly on local host port 8000. I put it in a hidden input field in my register form, then retrieve the cookie using js-cookie perfectly in auth.js (I can see this with console.log). I then send it with axios with the cookie in the header with withCredentials=true. I get the following error:

error

Forbidden (CSRF cookie not set.): /accounts/register
[28/Feb/2024 19:39:57] "POST /accounts/register HTTP/1.1" 403 2869

I have tried various other methods of sending the cookie. I have all the relevant CORS settings set.

views.py

@method_decorator(ensure_csrf_cookie, name='dispatch')
class GetCSRFToken(APIView):
    permission_classes = (permissions.AllowAny, )

    def get(self, request, format=None):
        return Response({ 'success': 'CSRF cookie set'})

auth.js

import axios from 'axios';
import {
    REGISTER_SUCCESS,
    REGISTER_FAIL
} from './types';
import Cookies from 'js-cookie'

export const register = (username, password, re_password) => async dispatch => {

    const config = {
        withCredentials: true,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRFToken': Cookies.get('csrftoken')
        }
    };

    const body = JSON.stringify({ username, password, re_password });

    try {

        const res = await axios.post(`${process.env.REACT_APP_API_URL}/accounts/register`, body, config);

        if (res.data.error) {
            dispatch({
                type: REGISTER_FAIL
            });
        } else {
            dispatch({
                type: REGISTER_SUCCESS
            })
        }
    } catch (err) {
        dispatch({
            type: REGISTER_FAIL
        });
    }
}

CSRFToken.js (get csrf token from here. This works)

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

const CSRFToken = () => {
    const [csrftoken, setcsrftoken] = useState('');

    const getCookie = (name) => {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            let cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                let cookie = cookies[i].trim();

                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get(`${process.env.REACT_APP_API_URL}/accounts/csrf_cookie`)

                setcsrftoken(getCookie('csrftoken'));
            } catch (err) {
                console.log("error");
            }
        }
        fetchData();
        
    }, []);
    
  return (
    <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />
  );
}

export default CSRFToken

html and js not working the same with flask

i have a folder which contains server.py a templates folder with index.html and a js folder with script.js
server.py:

from flask import Flask, render_template
import random

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sparkle Trail and Dust Cursor</title>
</head>
<body>
    <h1>Sparkle Trail and Dust Cursor</h1>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

script.js can be found here: https://codepen.io/sarahwfox/pen/pNrYGb its too long probably but yeah im trying to have this effect but it either doesnt show anything or it shows the trail following the cursor but not the + sparkles

How to unit test a @Query() decorator with Jest in NestJS?

I’m trying to write unit tests for my NestJS application using Jest. I have a resolver with a @Query() decorator that I want to test, but I’m not sure how to achieve 100% test coverage for the line that contains the @Query() decorator.

Here is the code for my resolver:

    @Resolver(() => Person)
    export class MyResolver {
      @Query(() => Person, { name: 'personLogged' })
      async getPerson(
        @Token() tokenPersonLogged: string,
        @Context() context,
        @Profiles() personProfiles: string[],
      ): Promise<Person> {
        // ...
      }
    }

Any help would be greatly appreciated!

Enhancing Random Word Generator Web App with Additional Features

I’m working on a web application that fetches a random uppercase word from an API and displays it on the webpage using JavaScript’s fetch API. I’m looking to add some features to improve user experience and functionality. Here’s the current code:



// API endpoint for fetching a random word
const apiUrl = 'https://random-word-api.vercel.app/api?words=1&length=5&type=uppercase';

// Variable to store the fetched word
let wordAPI = 0;

// Making a GET request to the API
fetch(apiUrl)
  .then(response => {
    // Handling HTTP errors
    if (!response.ok) {
      throw new Error(`Request failed with status code ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    // Storing the fetched word
    wordAPI = data[0];
    console.log('Generated Word:', wordAPI);
  })
  .catch(error => {
    // Handling errors during the API request
    console.error('Error getting the word:', error);
  });

I’m seeking guidance on implementing the following enhancements: Display the length of the generated word alongside the word itself. Add a “Generate New Word” button to fetch and display a new random word. Gracefully handle errors by showing user-friendly messages on the webpage. Include a loading indicator while waiting for the API response.

Disable screen while current process still run

I have a multiple record and image generation button. and each record take around 1 min to be generated one button submit. for example:

  1. cat playing guitar with his friends – [submit]
  2. Dog catch squirrel on tree – [submit]
  3. A school of dolphin play ice hockey – [submit]

The scenario is let said I submit no.1, I want to disable all button from submitting while the process still runs, and enable again after the process done.

The reason is I want to prevent user from clicking multiple time and multiple process.
I expecting the all the button to disable after no.1 button submitted. and after the process completed, all button enable again.

How to implement a word guessing game in JavaScript?

I’m developing a word guessing game in JavaScript and I have code similar to the following:

function intentar() {
  const INTENTO = leerIntento();
  if (INTENTO === palabra ) {
    terminar ("<h1>GANASTE!</h1>")
    return
  }
  for (let i in palabra) {
    if (INTENTO[i]===palabra[i]) {
      console.log(INTENTO[i], "VERDE")
    } else if( palabra.includes(INTENTO[i]) ) {
      console.log(INTENTO[i], "AMARILLO")
    } else {
      console.log(INTENTO[i], "GRIS")
    }
  }
  intentos--
  if (intentos==0){
    terminar("<h1>PERDISTE!</h1>")
  }
}

How do I implement the read Intent function to get user input?
Is there a more efficient way to check if the user’s intent matches the secret word?
How can I improve the readability and maintainability of my code?
I would appreciate any guidance or advice to optimize my implementation of the word guessing game in JavaScript. Thank you!

Sharing variables between the same file

All my 5 html files that all go to each other using links and share the same javascript script <script src="indexJS.js"></script> In the javascript file I have the following

let shoppingCart = []

function reply_click(clicked_id)
{
    shoppingCart.push(clicked_id);
    console.log(shoppingCart);
}

Basically when I click a button, I get the id of the button and then add it to an array. What I want to happen is when I go to another file, it says that shoppingCart array between files. Right now every time I go to a new HTML file, the shoppingCart array resets.

I DON’T want to use any other languages except javascript. No node or anything please, I’m not sure if its possible though.