Display a different image within same tag

I am trying to display a different image within the same tag when a different value is searched in a search bar. Here is the the html code as default when Pikachu is searched. I have provided all of the html as well as javascript that I have used. This is for a freeCodeCamp project called Pokemon Search App. Also when I add this code my “types.innerHTML” for “GHOST” and “POISON” is not displaying.

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>Pokemon Search App</title>
  </head>
  <body>
  <h1>Pokemon Search App</h1>
  <input id="search-input" required></input>
  <button id="search-button">Click Me</button>
  <p id="pokemon-name"></p>
  <p id="pokemon-id"></p>
  <p id="weight"></p>
  <p id="height"></p>
  <p id="types"></p>
  <p id="hp"></p>
  <p id="attack"></p>
  <p id="defense"></p>
  <p id="special-attack"></p>
  <p id="special-defense"></p>
  <p id="speed"></p>
  <img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/25.png" style="display: none;" id="sprite" class="pikachu-sprite">
  <script src="./script.js"></script>
  </body>
</html>     


Here is the javascript I am currently using to change it when 94 (Gengar) is searched.

const searchInput = document.getElementById("search-input");
const searchButton = document.getElementById("search-button");
const pokemonName = document.getElementById("pokemon-name");
const pokemonId = document.getElementById("pokemon-id");
const weight = document.getElementById("weight");
const height = document.getElementById("height");
const hp = document.getElementById("hp");
const attack = document.getElementById("attack");
const defense = document.getElementById("defense");
const specialAttack = document.getElementById("special-attack");
const specialDefense = document.getElementById("special-defense");
const speed = document.getElementById("speed");
const types = document.getElementById("types");
const pikachuImage = document.getElementById("sprite");






searchButton.addEventListener('click', function pikachuSearch() {
    if (searchInput.value.toLowerCase() === 'pikachu') {
        pokemonName.innerText = 'PIKACHU';
        pokemonId.innerText = '25';
        weight.innerText = 'Weight: 60';
        height.innerText = 'Height: 4';
        hp.innerText = '35';
        attack.innerText = '55';
        defense.innerText = '40';
        specialAttack.innerText = '50';
        specialDefense.innerText = '50';
        speed.innerText = '90';
        pikachuImage.style.display = "block";
        types.innerHTML = `<span>ELECTRIC</span>`;
    } else if (searchInput.value === '94') {
        pokemonName.innerText = 'GENGAR';
        pokemonId.innerText = '94';
        weight.innerText = '405';
        height.innerText = 'Height: 15';
        hp.innerText = '60';
        attack.innerText = '65';
        defense.innerText = '60';
        specialAttack.innerText = '130';
        specialDefense.innerText = '75';
        speed.innerText = '110';
        gengarImage.style.display = "block";
        types.innerHTML = `
        <span>GHOST</span>
        <span>POISON</span>`;
        changeImgSrc();
    } else if (searchInput.innerText = 'Red') {
        // Display an alert if the input is empty
        alert('Pokémon not found');
    }
});




function changeImageSrc() {
  pikachuImage.src = 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/94.png';
}
function changeImageSrc() {
  pikachuImage.src = '<https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/94.png>';
}

How to get WordPress mobile menu to trigger a javascript event based on css class?

I have code that triggers a slide in / out menu using a css class on a stardard wordpress menu item. It works fine on desktop but on mobile clicking the same menu link does not trigger the code.

Here is the jquery code:

<script>jQuery(document).ready(function($) {
    var dl_ButtonToggle = $('.dl-btn-toggle');
    var dl_SlideSidebar = $('.dl-slide-sidebar');
    dl_ButtonToggle.click(function(e) {
      e.preventDefault();
      dl_ButtonToggle.toggleClass('is-opened');
      dl_SlideSidebar.toggleClass('is-opened');
      dl_SlideSidebar.addClass('has-transition');
      dl_SidebarCheck();    
    })
    
    $('.dl-close').click(function() {
      $('.is-opened').removeClass('is-opened');
      dl_SidebarCheck();
    })
});</script> 

I use the css class .dl-btn-toggle on the wordpress menu item to trigger the slide in.

How can I make it work on mobile wordpress menu as well?

Can I make Three.JS animated cubes light up randomly synced to an audio track?

I am currently creating an audio visualizer using three.js models in javascript, html and css.

I am trying to figure out how to get the three.js animated cubes to light up and sync up with an audio track

but cannot figure out how to do this. Any direction or advice is welcome I have searched for a while now everywhere and cannot seem to find anything relevant to what I am trying to accomplish.

This is the script.js I have so far for the animated cubes. I have tried various methods that I found online via here, codepen and youtube but nothing I find is even close to what I am trying to achieve. I know this can be done with just html and css animation but I would rather use Javascript as I believe it would look better as my final project.

function auth () {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    if(username =="JohnP23" && password == "John123") {
        window.location.assign("visual.html");
        alert("Login Succesful!")
    }
    else {
        alert("Invalid Username and Password")
        return;
    }
}

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

camera.position.z = 10;
const renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const cubes = [];
const numCubes = 1000;
const cubeSize = 0.5;
const cubeEdgesMaterial = new THREE.LineBasicMaterial({
color: 0x000000 });
for(let i = 0; i < numCubes; i++) {
    const cubeGeometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize)
    const cubeMaterial = new THREE.MeshBasicMaterial ({color: Math.random() * 0xffffff, transparent: true, opacity: 1 });

    const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
    cube.position.x = (Math.random() - 0.5 ) * 50;
    cube.position.y = (Math.random() - 0.5 ) * 50;
    cube.position.z = (Math.random() - 0.5 ) * 50;
    cube.rotation.x = Math.random() * Math.PI;
    cube.rotation.y = Math.random() * Math.PI;
    cube.rotation.z = Math.random() * Math.PI;

    const edges = new THREE.EdgesGeometry(cubeGeometry);
    const line = new THREE.LineSegments(edges, cubeEdgesMaterial);

    cube.add(line);
    cubes.push(cube);
    scene.add(cube);

}

function animate() {
    requestAnimationFrame ( animate );
    cubes.forEach(cube => {
        cube.rotation.x += Math.random() * 0.005;
        cube.rotation.y += Math.random() * 0.005;
        cube.rotation.z += Math.random() * 0.005;
    });

    const time = Date.now() * 0.0005;
    camera.position.x = Math.sin( time ) * 2;
    camera.position.y = Math.cos( time ) * 2;

    camera.lookAt( scene.position );
    renderer.render(scene, camera);

}

animate();

[ERR_INVALID_ARG_TYPE]: The”key” argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, DataView, KeyObject, or CryptoKey

got the error on the title when executing the function executeNewOrder, it seems to be something about the format of the signature, maybe something about the string or type, could anyone help?

import axios from "axios";
import crypto from "crypto";

const apiKey = process.env.API_KEY;
const apiSecret = process.env.API_SECRET;
const apiUrl = process.env.API_URL;

export async function executeNewOrder(symbol, quantity, side, price) {
  const data = {
    symbol,
    quantity,
    side,
    price,
    type: "LIMIT",
    timeInForce: "GTC",
  };

  const timeStamp = Date.now();
  const recvWindow = 50000;
  // limite de tempo para executar ordem

  const signature = crypto.createHmac("sha256", apiSecret).update(
    `${new URLSearchParams({
      ...data,
      timeStamp,
      recvWindow,
    }).toString()}`.digest("hex")
  );

  const newData = { ...data, timeStamp, recvWindow, signature };
  const qs = `?${new URLSearchParams(newData).toString()}`;

  const result = await axios({
    method: "POST",
    url: `${apiUrl}/v3/order${qs}`,
    headers: { " X-MBX-APIKEY": apiKey },
  });

  return result;
}

Why is Prisma Migrate detecting a drift and explaining it as foreign keys were removed and then the same foreign keys were added again?

I have an ongoing web app project on a NextJS prisma MySQL 8 stack hosted on Heroku. It’s been running smoothly in production for about 6 months. At the end of 2023, my MySQL 5.6 DB hosting plan was being retired and I was forced to change plans and upgrade to MySQL 8, restoring my DB from a mysqldump.
Now when I run npx prisma migrate dev I am getting the following error:

Drift detected: Your database schema is not in sync with your migration history.

The following is a summary of the differences between the expected database schema given your migrations files, and the actual schema of the database.

It should be understood as the set of changes to get from the expected schema to the actual schema.

[*] Changed the `group` table
  [-] Removed foreign key on columns (createdById)
  [+] Added foreign key on columns (createdById)

[*] Changed the `groupmember` table
  [-] Removed foreign key on columns (groupId)
  [-] Removed foreign key on columns (userId)
  [+] Added foreign key on columns (groupId)
  [+] Added foreign key on columns (userId)

This makes no sense to me. It is describing the drift as “a foreign key was removed, then the same foreign key with the same name was added”.
I am unable to use prisma migrate resolve --applied because all of my migrations have already been applied, and I cannot create a new migration because of this drift issue.

Max Listener Error: How to close listeners in node.js

I am getting a Max listener error and I believe it’s coming from this part of my code. How do I close the listeners. Please see code below.

  initiateWorker(file, workTask) {
    const worker = new Worker(path.resolve(file));
    worker.on('message', (result) => {
        if (result.success) {
            workTask.done(null, JSON.parse(result.response));
        } else {
            workTask.done(result.error, null);
        }
        this.removeWorker(worker);
    });
    worker.on('error', (err) => {
        workTask.done(err, null);
        this.removeWorker(worker);
    });
    worker.on('exit', () => {
        workTask.done(null, null);
        this.removeWorker(worker);
    });
    return worker;
}

removeWorker(worker) {
    this.workers.splice(this.workers.indexOf(worker), 1);
    worker.terminate();
}

I have tried modifying the code, adding removeListner. But I might be doing it incorrectly.

Why won’t my else if or else function work when the first one does? [closed]

I’m trying to use else/if statements to return different values based on what was clicked. Now, my code works for the first if, but suddenly does not for the rest. I can’t understand why. Every button I have has a different ID, so when the button with the “small” ID is pressed, it changes the head1 to “Small”. When the button with the “medium” Id is pressed, it does nothing, and continues to display “Small”. Can anyone help the else if and else statement run?

document.querySelector(".pizza").addEventListener('click', function(){
    if (document.getElementById("small") == event.target) {
        Size_Price = 5;
        document.getElementById("head1").textContent = "Small";
}       else if (document.getElementById("medium") == event.target) {
            Size_Price = 10;
            document.getElementById("head1").textContent = "Medium";
}           else { 
                Size_Price = 18;
                document.getElementById("head1").textContent = "Fatso"
}
})

How to get next 5 records based on current id of a field in graphql or do something like next videos in youtube example

I want to get next 5 records based on current id that i have stored in context , how to get them and map them in the component for rendering only by having current id field,
suppose I have the id of current field already provided by context,
i want achieve something like Youtube next videos

<div>
  <VideoPlayer
                height="493px"
                width="793px"
                url={videoUrl}
                key="1"
              />

<div className="nextVideos">
<h2>Next vidoes</h2>
<ul>
<li>
?????
</li>
</ul>
</div>
</div>

Parcel: no hot reloading and no minifying

I have a WordPress theme which I have added Parcel to. Watching and building works fine, but there is no hot reloading and no minification. I have spent some time with the Parcel docs but can’t find anything specific on how to get this working.

My entry point index.js contains:

import './js/main.js';
import './sass/style.scss';

Those two files in turn include other files within their respective directories.

As I mentioned, changing any SCSS or JS is correctly triggering a rebuild. But it doesn’t trigger any refresh or HMR in the browser. Do I need to add a configuration file to explicitly make it refresh, and if so what should that contain?

The second issues is that when running ‘build’ there is no minification happening. Again I’m guessing I need to specifically configure something.

Both of these issues surprise me, since I thought these were default behaviours. I’m guessing this has something to do with the nested directories.

These are the relevant parts of my package.json:

  "devDependencies": {
    "@wordpress/scripts": "^19.2.2",
    "cssnano": "^4.1.11",
    "dir-archiver": "^1.1.1"
  },
  "scripts": {
    "watch": "parcel watch src/index.js --out-dir dist",
    "build": "parcel build src/index.js --out-dir dist"
  }

Rails Quiz save Answers True or False

How can I get the radio button onclick to load a div with the correct answer and answer description. I have a quiz_question model and controller where the correct answer and answer description are being saved.

.row#quiz-record-questions
  .col-md-12
- quiz_questions.each_with_index do |quiz_question, i|
  - if quiz_question.question.present?
    = f.hidden_field :quiz_question_id, value: quiz_question.id
    .row
      .col-sm-8
        %b.pull-left{style: 'width: 25px'}= i+1
        .pull-left{style: 'width: calc(100% - 25px);'}
          %p.no-margin.no-padding= sanitize(quiz_question.question, tags: %w(i em))
      .col-sm-4
        .btn-group.btn-group-justified{'data-toggle' => 'buttons'}
          - if params[:quiz_record]
            - current_state = params[:quiz_record][:answer.to_sym]
          - checked = current_state == 'false' || current_state =='true' ? "" : true

          %label{class: "btn btn-default btn-sm #{current_state == 'true' ? 'active' : ''}"}
            = radio_button :answer.to_sym, true, autocomplete: 'off'
            True
          %label{class: "btn btn-default btn-sm #{current_state == 'false' ? 'active' : ''}"}
            = radio_button :answer.to_sym, false, autocomplete: 'off'
            False
          %label{class: "blank-question-form"}
            = radio_button :answer.to_sym, 'empty', autocomplete: 'off', checked: checked

    %hr.small-margin

Expo – Invariant Violation: requireNativeComponent: “RNCViewPager” was not found in the UIManager

I recently integrated @react-navigation/material-top-tabs into my React Native app managed by Expo to implement the navigation stack. The implementation in question:

import React from 'react';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { TransitionPresets, CardStyleInterpolators } from '@react-navigation/stack';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';

import Posts from '../../components/activities/Sept/Posts';

import {headerRight} from '../../components/header/headerRight';

import styles from '../bottom/styles';

const Stack = createMaterialTopTabNavigator();


/**
 * Renders the navigation container for the Sept stack.
 * 
 *
 *
 * @returns {JSX.Element} 
 */

export default function SeptNavigator({ route }) {
    const drawerNavigation = useNavigation();

    const { septId } = route.params;
    console.log('SeptNavigator:', septId);
    
    return (
        <NavigationContainer independent={true}>
            <Stack.Navigator
                initialRouteName='Posts'
                backBehavior="none"
                screenOptions={({route}) => ({

                    headerRight: () => headerRight({route, drawerNavigation}),

                    headerTitleAlign:'center',
                    headerStyle: styles.header,
                    headerTitleStyle: styles.headerTitle,
                    headerMode :'screen',

                    gestureEnabled: true,
                    gestureDirection: 'horizontal',
                    gestureResponseDistance: 500,
                    gestureVelocityImpact: 2,

                    ...TransitionPresets.SlideFromRightIOS,
                    
                    cardOverlayEnabled: true,

                })}
                >

                <Stack.Screen name="Posts">
                    {(props) => <Posts {...props} septId={septId} />}
                </Stack.Screen>
            </Stack.Navigator>
        </NavigationContainer>    
    );
};

However, I encountered the following error:

Invariant Violation: requireNativeComponent: "RNCViewPager" was not found in the UIManager.

After some research, I found suggestions that rebuilding the app might solve the issue. This didn’t work with eas build. To figure out more, I ran ./gradlew, but faced the following gradle-related errors:

1: Task failed with an exception.
-----------
* Where:
Build file '/path/to/node_modules/expo-firebase-core/android/build.gradle' line: 40

* What went wrong:
A problem occurred evaluating project ':expo-firebase-core'.
> Could not set unknown property 'classifier' for task ':expo-firebase-core:androidSourcesJar' of type org.gradle.api.tasks.bundling.Jar.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':expo'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
==============================================================================

Here are the project dependencies as stated in package.json:

"dependencies": {
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
    "@babel/plugin-proposal-optional-chaining": "^7.21.0",
    "@babel/plugin-transform-arrow-functions": "^7.22.5",
    "@babel/plugin-transform-shorthand-properties": "^7.22.5",
    "@babel/plugin-transform-template-literals": "^7.22.5",
    "@babel/preset-env": "^7.22.10",
    "@bacons/expo-router-top-tabs": "^0.1.0",
    "@callstack/react-theme-provider": "^3.0.9",
    "@expo/config-plugins": "~7.2.2",
    "@expo/prebuild-config": "~6.2.4",
    "@expo/webpack-config": "^19.0.0",
    "@react-native-community/hooks": "^3.0.0",
    "@react-native-firebase/app": "^18.7.3",
    "@react-native-firebase/auth": "^18.3.0",
    "@react-native-picker/picker": "2.4.10",
    "@react-navigation/bottom-tabs": "^6.5.8",
    "@react-navigation/drawer": "^6.6.3",
    "@react-navigation/material-top-tabs": "^6.6.5",
    "@react-navigation/native": "^6.1.7",
    "@react-navigation/native-stack": "^6.9.13",
    "@react-navigation/stack": "^6.3.17",
    "@reduxjs/toolkit": "^1.9.5",
    "@rneui/base": "^4.0.0-rc.8",
    "@rneui/themed": "^4.0.0-rc.8",
    "@rnmapbox/maps": "^10.1.2",
    "atob": "^2.1.2",
    "base-64": "^1.0.0",
    "eas": "^0.1.0",
    "eas-cli": "^4.1.2",
    "expo": "^49.0.7",
    "expo-av": "~13.4.1",
    "expo-blur": "~12.4.1",
    "expo-build-properties": "^0.8.3",
    "expo-constants": "~14.4.2",
    "expo-crypto": "~12.4.1",
    "expo-firebase-recaptcha": "^2.3.1",
    "expo-image-picker": "~14.3.2",
    "expo-linking": "~5.0.2",
    "expo-router": "^2.0.0",
    "expo-splash-screen": "~0.20.5",
    "expo-status-bar": "~1.6.0",
    "firebase": "^10.4.0",
    "global": "^4.4.0",
    "gradle": "^1.2.4",
    "lodash": "^4.17.21",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-firebase-hooks": "^5.1.1",
    "react-native": "0.72.6",
    "react-native-confirmation-code-field": "^7.3.2",
    "react-native-element-dropdown": "^2.10.0",
    "react-native-gesture-handler": "~2.12.0",
    "react-native-pager-view": "6.0.1",
    "react-native-paper": "^5.10.4",
    "react-native-reanimated": "~3.3.0",
    "react-native-redash": "^18.1.0",
    "react-native-safe-area-context": "4.6.3",
    "react-native-screens": "~3.22.0",
    "react-native-stretchy": "^4.0.0",
    "react-native-svg": "13.9.0",
    "react-native-swiper": "^1.6.0",
    "react-native-tab-view": "^3.5.2",
    "react-native-vector-icons": "^10.0.0",
    "react-native-viewpager": "^0.2.13",
    "react-native-web": "~0.19.6",
    "react-native-webview": "13.2.2",
    "react-redux": "^8.1.2",
    "redux": "^4.2.1",
    "redux-thunk": "^2.4.2",
    "typescript": "^5.1.3"
  },

Finally, here’s some system information I received when running ./gradlew --version:


------------------------------------------------------------
Gradle 8.0.1
------------------------------------------------------------

Build time:   2023-02-17 20:09:48 UTC
Revision:     68959bf76cef4d28c678f2e2085ee84e8647b77a

Kotlin:       1.8.10
Groovy:       3.0.13
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          17.0.10 (Oracle Corporation 17.0.10+7)
OS:           Linux 5.15.131-1-MANJARO amd64

I’m seeking guidance on resolving the “RNCViewPager” error and successfully rebuilding the app with Expo. Any insights into the cause of these errors or suggestions for resolving them would be greatly appreciated.

Accesing a webpage’s on-click events inside a chrome popup extension

I am trying to create a chrome extension that should be able to track any click events on the current webpage (outside of the extension). I have tried adding event listeners and content-scripts, but I can only access click events within the extension and not outside of it. Is there any way to do this?

This is my manifest file:

{
    "manifest_version": 3,
    "name": "Your Extension",
    "version": "1.0",
    "permissions": [
      "activeTab",
      "tabs"
    ],
    "browser_action": {
      "default_popup": "popup.html"
    },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["content.js"],
        "run_at": "document_start" 
      }
    ]
  }

My popup.html:

<!-- popup.html -->
<!DOCTYPE html>
<html>
<head>
  <title>Popup</title>
  <script src="content.js"></script>
</head>
<body id="your-popup-id">
    <span>This is my popup extension</span>  
</body>
</html>

My content.js file:

window.addEventListener('click', myClickListener, true);

function myClickListener(e) {
    alert("You clicked on " + e.target);
}

The alert fires whenever I click inside the popup extension, but it doesn’t fire when I click outside of it within the current tab. The popup extension either closes or does nothing even if open.

I have tried a couple of answers from stackoverflow, but haven’t gotten anywhere with this.

Any help would be appreciated.

Android Chrome 121.0.6167.102 breaks my reactjs site

My football simulator site is broken on my POCO M5 phone like in the screenshot below after updating Android Chrome to 121.0.6167.102. The UI elements just breaks as scrolling down the fixtures. You can check out the recording of this issue at https://youtube.com/shorts/96-83oynNhs?feature=shared

The site uses reactjs and mantine. I have another old RedMi phone that uses 121.0.6167.101 and it has no issues at all. Clearing chrome cache doesn’t fix it. Do you know what changes in chrome causing this issue?

enter image description here

enter image description here

How to pass a the image src to a function to update another image

I have a number of images that when clicked seek an HTML5 player to a given times:

<img class="ib" src="/image1.PNG" onclick="player.setCurrentTime(500)">
<img class="ib" src="/image2.PNG" onclick="player.setCurrentTime(1000)">
<img class="ib" src="/image3.PNG" onclick="player.setCurrentTime(1200)">
<img class="ib" src="/image4.PNG" onclick="player.setCurrentTime(1500)">
<img class="ib" src="/image5.PNG" onclick="player.setCurrentTime(1800)">
<img class="ib" src="/image6.PNG" onclick="player.setCurrentTime(2000)">

What I would also like is the below source changed to the source of the image clicked:

<img id="large-image" src="/image1.PNG">

the following jquery does part of what I need- I coded in the change to image 2, id like to pick up the src of the image clicked to change the source on large-image: in the bellow /image2.PNG needs to be a variable.

$(document).ready(function() {
       $('.ib').click(function() {
        $('#large-image').attr('src', '/image2.PNG');
        });
        });

WEBPACK_IMPORTED_MODULE_2__.useFavorites is not a function

I’m trying to make a favorites button and a favorites page that will show the added countries. It’s Next.js. I get this error:

(0 , _contexts_favoriteContext__WEBPACK_IMPORTED_MODULE_2__.useFavorites) is not a function

favoriteContext.jsx file:

"use client";
import { createContext, useContext, useState } from "react";

const FavoritesContext = createContext();

export const FavoritesProvider = ({ children }) => {
  const [favorites, setFavorites] = useState([]);

  const addFavorite = (country) => {
    setFavorites((prevFavorites) => [...prevFavorites, country]);
  };

  return (
    <FavoritesContext.Provider value={{ favorites, addFavorite }}>
      {children}
    </FavoritesContext.Provider>
  );
};

export const useFavorites = () => {
  return useContext(FavoritesContext);
};

Favorites page:

import React from "react";
import { useFavorites } from "../contexts/favoriteContext";

const Favorites = () => {
  const { favorites } = useFavorites();
  return (
    <div>
      <h1>Favoriler</h1>
      <ul>
        {favorites.map((favorite, index) => (
          <li key={index}>{favorite.name}</li>
        ))}
      </ul>
    </div>
  );
};
export default Favorites;

If there are any other files you want to see, I can add them.