Redux does not change values

my Redux does not change the variables value. I am trying to test out Redux but I really cant find what I am doing wrong. For now I am only trying to Log a value but the value does not change.

This is my ReduxActions:

export const TEST_FUNC = 'TEST_FUNC';

export const testFunc = () => {
    
    const theTestingString = "TAG testing redux";

    return {
        type: TEST_FUNC,
        payload: theTestingString
    }
}

In my Reducer I give the variable a initial value, and in my Actions file I am trying to change that value but when I console.log(testRedux) I only get the initial value. here is my Reducer:

import { TEST_FUNC } from "../actions/firebaseActions";

const initialState = {
    theTestingString: 'Initial Value',
}

export default function(state = initialState, action) {

        switch(action.type) {
            case TEST_FUNC: 
            console.log("HSKJDKJSKFDBSKJKAJDL")
            return {
                ...state,
                theTestingString: action.payload
            }
        }

        return state;
}

Here is my Store:

import {createStore, applyMiddleware, combineReducers} from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';

import firebaseReducer from './reducers/firebaseReducer';

const rootReducer = combineReducers({
    firebaseTest: firebaseReducer
});

const middleware = composeWithDevTools(applyMiddleware(thunk));

export default createStore(rootReducer, middleware);

Here is where I am trying to log the value:

import { useNavigation } from '@react-navigation/native';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import {Button, Card, TextInput} from 'react-native-paper';
import { FirebaseContext } from '../../context/FirebaseContext';
import React, {useContext, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';

const initialUserState = {
    userName: 'Nicole Lopez',
    password: '1001008888',
}

export default function LoginScreen() {
    const [disabled, setDisabled] = useState(false);
    const [userState, setUserState] = useState(initialUserState);
    const testRedux = useSelector(state => state.firebaseTest.theTestingString);
    //const fbContext = React.useContext(FirebaseContext);
    const navigation = useNavigation();

    console.log("Logging right away: " + testRedux);

    const onInputChange = (field, value) => {
        setUserState({
            ...userState,
            [field]: value
        })
    }

    useEffect(() => {
        setDisabled(userState.userName.length === 0 || userState.password.length === 0);
    }, [userState.userName, userState.password])

  return (
    <View style={styles.container}>
            <Card style={styles.card}>

                <TextInput
                    mode="outlined"
                    label="Förnamn & Efternman"
                    defaultValue={userState.userName}
                    onChangeText={text => onInputChange("username", text)}
                    right={<TextInput.Icon name="account" onPress={() => {
                    }}/>}
                    style={styles.textInput}/>

                <TextInput
                    mode="outlined"
                    label="Anställningsnummer 100100xxxx"
                    defaultValue={userState.password}
                    right={<TextInput.Icon name="lock"/>}
                    onChangeText={text => onInputChange("password", text)}
                    style={styles.textInput}/>
            </Card>

            <View style={styles.buttonRow}>

                <Button
                    color={disabled ? "gray" : undefined}
                    disabled={disabled}
                    mode={'contained'}
                    icon={'login'}
                    onPress={() => {
                        //console.log("The func: " + testRedux)
                        console.log("The variable: " + testRedux)
                        //console.log(fbContext)
                        //console.log("TAG isUserSignedIn: " + fbContext?.isuserSignedIn)
                        //console.log("TAG testLog:::: " + fbContext?.testLog())
                        //fbContext?.testLog()
                        //console.log("TAG LOGIN BTN PRESSED")
                        //navigation.navigate('HomeScreen')
                    }}>Login</Button>
            </View>
        </View>
  );
}

This is my App.js:

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import {StackScreens} from './src/helpers/types';
import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import LoginScreen from './src/screens/LoginScreen/LoginScreen';
import HomeScreen from './src/screens/HomeScreen/HomeScreen';
import {doc, getFirestore, onSnapshot, setDoc, Unsubscribe as UnsubscribeFS} from 'firebase/firestore';
import { FirebaseContextProvider, FirebaseContext } from './src/context/FirebaseContext';
import { useContext } from 'react';
import {Provider} from 'react-redux';

import store from './src/redux/Store';


const Stack = createNativeStackNavigator();

export default function App() {
  return (
    <Provider store={store}>
      <Content />
    </Provider>  
  );
}

export const Content = () => {

  const navigationRef = useNavigationContainerRef();
  const firebaseContext = useContext({FirebaseContext});

  return (
    
    <NavigationContainer ref={navigationRef}>
        <Stack.Navigator initialRouteName="LoginScreen">
          <Stack.Screen name="LoginScreen" component={LoginScreen} />
          <Stack.Screen name="HomeScreen" component={HomeScreen} /> 
        </Stack.Navigator>
      </NavigationContainer>
      
  );
}

I am new to ReactNative, I have tried Context but I got a similar issue, maybe I’m doing something in the wrong order?

what is making props behavior inconsistent when set as a variable and passed into another function

I am creating a simple audio player using React.

When pushing the “Play” button, audio will be played from a url and the button will display “Pause”. Once the audio is finished the button will reset to “Play.”

There are three buttons “one” “two” “three”. Each one will load a new audio url to be played by the button. Here is the codesandbox.

I’m new to useEffect and useState and I think there is an issue with how I’m updating this with props.

In my audio player component, if I directly set the url (without updating it with props), the audio will play as expected when the “play” button is pushed. However, when I set the url with props it won’t play (even though the console.log() displays the correct url).

here is my Audio3.js component (responsible for playing audio:

import React, { useState, useEffect } from "react";


const useAudio = (url) => {
  console.log("in useAudio", url)
  const  = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);


  const toggle = () => setPlaying(!playing);

  useEffect(() => {
    playing ? audio.play() : audio.pause();
  }, [playing]);

  useEffect(() => {
    audio.addEventListener("ended", () => setPlaying(false));
    return () => {
      audio.removeEventListener("ended", () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = (props) => {

console.log("the current page is", props.currPage)

  // const url = "https://github.com/cre8ture/audioFilesForBL/blob/main/2.mp3?raw=true"

  const url =  "https://github.com/cre8ture/audioFilesForBL/blob/main/" +
  props.currPage +
  ".mp3?raw=true"
  
  console.log("the audio 3 is ", url);
  const [playing, toggle] = useAudio(url);


  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
};

export default Player;

Here is the threeButtons.js file:

import React from "react";

function Tabs(props) {
  return (
    <>
      <button onClick={() => props.handleChangeProps(1)}>ONE</button>
      <br />
      <button onClick={() => props.handleChangeProps(2)}>TWO</button>
      <br />
      <button onClick={() => props.handleChangeProps(3)}>THRE</button>
    </>
  );
}

export default Tabs;

Here is the header component that houses the audio Play button:

import React from "react";
import Audio from "./Audio3";

function Header(props) {
  console.log("header", props.currPage);

  return (
    <Audio currPage={props.currPage} />
  );
}

export default Header;

And lastly, here is my App.js

import React, { useState } from "react";
import Header from "./components/header";
import ConceptTabs from "./components/threeButtons";

function App() {
  const [pageID, setPageID] = useState(0);

  // goes to ConceptTabs
  let handleChange = (id) => {
    console.log("clicked", id);
    handleChange2(id);
    setPageID(id);
    return id;
  };

  // Goes to Audio2
  let handleChange2 = (id) => {
    console.log("clicked2", id);
    return id;
  };

  console.log("pageID", pageID);

  return (
    <>
      <Header currPage={pageID} />
      <br />
      <ConceptTabs handleChangeProps={handleChange} />
    </>
  );
}

export default App;

Thanks so much

get the static part of a RegExp

I want to get the static part of a RegExp string, which 100% guaranteed to not have a regex-specific characters, except the grouping parentheses ().

for instance, this regex /path/config-(.+)/.js/ has a static part /path/config- until the character ‘.’

use cases:

I want to search for all matched entries inside a folder that have too many files and subfolders.

so, it is a bit faster to start searching from the basic path /path that doesn’t needed to be matched against, instead of starting from the root directory.

Read and edit local xml-file in Javascript

I have a directory that contains

--index.html
--script.js
--file.xml

and I want to read the content of the file.xml as a string in order to replace a few words within the xml-file. (Later on I would like to send the edited xml-file as e-mail).

I managed to access to xml-file, but did not manage to save the whole content in a string and/or replace some known keywords within the xml.

This is where I got so far:

var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

function reportStatus2() {
  if (oXHR.readyState == 4)               // REQUEST COMPLETED.
     console.log(this.responseXML)        // This gets me the XML-document, but I want the complete xml content as string
}
oXHR.onreadystatechange = reportStatus2;    
oXHR.open("GET", "../file.xml", true);
oXHR.send();

I found so many posts on that topic here, but none was able to answer my question!
Any ideas?

Finding the longest connection of ports (JS)

I can’t solve a problem.
We have an array. If we take a value, the index of it means port ID, and the value itself means the other port ID it is connected to. Need to find the start index of the longest sequential connection to element which value is -1.

I made a graphic explanation to describe the case for the array [2, 2, 1, 5, 3, -1, 4, 5, 2, 3]. On image the longest connection is purple (3 segments).

graphic description

I need to make a solution by a function getResult(connections) with a single argument. I don’t know how to do it, so i decided to return another function with several arguments which allows me to make a recursive solution.

function getResult(connections) {
  return f(connections.findIndex(e => e == -1), connections, 0, []);
}

function f(index, cnx, counter, branches) {
  counter++;  
  for (let i = 0; i < cnx.length; i++) {
    if (cnx[i] === index) {
      branches.push([i, counter]);
      return f(i, cnx, counter, branches);
    }
  }
  return branches.sort((a, b) => b[1] - a[1])[0][0];
}

console.log(getResult([1, 2, -1])); // expected 0
console.log(getResult([1, -1, 1, 2])); // expected 3
console.log(getResult([2, 1, -1])); // expected 0
console.log(getResult([3, 4, 1, -1, 3])); // expected 2
console.log(getResult([1, 0, -1, 2])); // expected 3
console.log(getResult([3, 2, 1, -1])); // expected 0
console.log(getResult([2, 2, 1, 5, 3, -1, 4, 5, 2, 3])); // expected 6

Anyway, the code doesn’t work completely properly.
Would you please explain my mistakes?
Is it possible to solve the problem by a function with just one original argument?

Create a student timetable using React JS

I’m looking to develop a Timetable for students using React JS to manage their classes online, as you see in some timetable apps in Google Play & App Store. Still, my problem is finding the package to create this timetable.

I couldn’t find any timetable package to use in my app. Can someone please help and suggest a timetable for students?

React Router V6: same Component rendering in multiple routes not updating

This is my App.js:

<Provider store={store}>
        <Header />
        <Routes>
          { categories.map(({ category }) => {
            return (
              <Route 
                key={name}
                exact path={`/${category}`}
                element={<Category name={name} />}
              />
            )
          }) }
        </Routes>
      </Provider>

Category.jsx:

export class Category extends Component {
  render() {
    const { name } = this.props;
    return (
      <div>
        <h1>{name}</h1>
        <CategoryBody name={name} />
      </div>
    );
  }
}

export default Category;

CategoryBody.jsx:

export default class CategoryBody extends Component {
  constructor() {
    super();
    this.state = {
      products: [],
    };
  }

  componentDidMount() {
    const path = window.location.pathname;
    const selectedCategory = path === "/" ? "all" : path.split("/")[1];

    client
      .query({
        query: PRODUCTS_QUERY,
        variables: { title: `${selectedCategory}` },
      })
      .then((result) =>
        this.setState({ products: result.data.category.products })
      );
  }

  render() {
    const { products } = this.state;
    return (
      <div className="category-container">
        {products.map(({ id, name, inStock, gallery, prices, brand }) => {
          return (
            <ProductCard
              key={id}
              id={id}
              name={name}
              inStock={inStock}
              gallery={gallery}
              prices={prices}
              brand={brand}
            />
          );
        })}
      </div>
    );
  }
}

This is working fine when I change routes reloading the page. But when I change routes through nav links in my Header, the props name is updated, but the rest of the application is not.

Specifically, the API call in componentDidMount() of CategoryBody.jsx is needed to be called again so that the items rendered in the component are the expected, according to the path.

I would like to know how can I “force update” a component when I change routes from inside the application.

Keep counter value to localStorage after page refresh

I have a countdown timer. This timer is called in an ajax call whenever user press a button.
I would like to set timer (countdown) in localStorage and get timer (countdown) after page refresh. Could you please help me to implement this in the below code?

const progressBox = document.getElementById('progress-box')

const activateProgress = (progress) => {

    if (progress.toString().length < 2) {
        progressBox.innerHTML = `<b>0${progress}:00</b>`
        progressBox.innerHTML = `<b>${progress}:00</b>`
    } else {
        progressBox.innerHTML = `<b>${progress}:00</b>`
    }
    
    let minutes = progress - 1
    let seconds = 60
    let displaySeconds
    let displayMinutes
    
    const timer = setInterval(()=>{
        seconds --
        if (seconds < 0) {
            seconds = 59,
            minutes --
        }
        if (minutes.toString().length < 2) {
            displayMinutes = '0' + minutes
        } else {
            displayMinutes = minutes
        }
        if (seconds.toString().length < 2) {
            displaySeconds = '0' + seconds
        } else {
            displaySeconds = seconds
        }
        if (minutes === 0 && seconds === 0) {
            setTimeout(()=>{
                clearInterval(timer)
                alert('Time Over')
            }, 500)
        }
        progressBox.innerHTML = `<b>${displayMinutes}:${displaySeconds}</b>`
    }, 1000)
}

const checkInForms = [...document.getElementsByClassName('checkin-forms')]
checkInForms.forEach(form=> form.addEventListener('submit', e=>{
    e.preventDefault()
    const clickedCheckinId = e.target.getAttribute('data-form-id')
    const clickedCheckinBtn = document.getElementById(`mark-checkin-btn-${clickedCheckinId}`)

    $.ajax({
        type: 'POST',
        url: "checkin/",
        data: {
            'csrfmiddlewaretoken': csrftoken,
            'pk': clickedCheckinId,
        },
        success: function(response){
            console.log(response)
            activateProgress(response.progress)
            localStorage.setItem('progress', response.progress)
        },
        error: function(error){
            console.log(error)
        }
    })
}))

Many Thanks

How to find out how many milliseconds until YouTube is ready?

You will notice that clicking on the play button too soon, and nothing happens. https://jsfiddle.net/zqrLxevo/

How the code works is: As soon as a video has loaded, click on the cover to start playing.

Is there a way to determine, or find out how many milliseconds it takes until youtube is ready?

How many milliseconds until the play button is able to be clicked?

I think it is higher than 500ms, but how is the number found out?

Is there a way I can attach something to it that will give me a number?

const manageCover = (function makeManageCover() {
  const events = {};

  function show(el) {
    el.classList.remove("hide");
  }

  function hide(el) {
    el.classList.add("hide");
  }

  function openCurtain(cover) {
    hide(cover);
    const curtain = document.querySelector(".curtain");
    curtain.classList.add("slide");
    return curtain;
  }

  function showVideo(curtain) {
    const thewrap = curtain.parentElement.querySelector(".wrap");
    show(thewrap);
  }

  function coverClickHandler(evt) {
    const cover = evt.currentTarget;
    const curtain = openCurtain(cover);
    showVideo(curtain);
    cover.dispatchEvent(events.afterClickCover);
  }

  function init(callback) {
    const cover = document.querySelector(".play");
    cover.addEventListener("click", coverClickHandler);
    events.afterClickCover = new Event("afterClickCover");
    cover.addEventListener("afterClickCover", callback);
  }

  return {
    init
  };
}());

const videoPlayer = (function makeVideoPlayer() {
  const events = {};
  const eventHandlers = {};
  let player = null;


  function loadIframeScript() {
    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    const firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }

  function onYouTubeIframeAPIReady() {
    const cover = document.querySelector(".play");
    const wrapper = cover.parentElement;
    const frameContainer = wrapper.querySelector(".video");
    videoPlayer.addPlayer(frameContainer);
  }

  function shufflePlaylist(player) {
    player.setShuffle(true);
    player.playVideoAt(0);
    player.stopVideo();
  }

  function onPlayerReady(event) {
    player = event.target;
    player.setVolume(100);
    shufflePlaylist(player);
    const iframe = player.h;
    iframe.dispatchEvent(events.afterPlayerReady);
  }

  function addPlayer(video) {

    const playlist = "0dgNc5S8cLI,mnfmQe8Mv1g,-Xgi_way56U,CHahce95B1g";

    const config = {
      height: 360,
      host: "https://www.youtube-nocookie.com",
      width: 640
    };
    config.playerVars = {
      autoplay: 0,
      cc_load_policy: 0,
      controls: 1,
      disablekb: 1,
      fs: 0,
      iv_load_policy: 3,
      loop: 1,
      playlist,
      rel: 0
    };
    config.events = {
      "onReady": onPlayerReady
    };

    player = new YT.Player(video, config);

    const iframe = player.h;
    const eventHandler = eventHandlers.afterPlayerReady;
    iframe.addEventListener("afterPlayerReady", eventHandler);
  }

  function play() {
    player.playVideo();
  }

  function addEvents(handlers) {
    eventHandlers.afterPlayerReady = handlers.afterPlayerReady;
    events.afterPlayerReady = new Event("afterPlayerReady");
  }

  function init(initEventHandlers) {
    addEvents(initEventHandlers);
    loadIframeScript();
    window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
  }

  return {
    addPlayer,
    init,
    play
  };
}());

videoPlayer.init({
  afterPlayerReady: function initCover() {
    manageCover.init(function playVideo() {
      videoPlayer.play();
    });
  }
});

Getting the file size of a file in javascript

<input id="archivo" name="archivo" type="file">

So my field of type file is called archivo which parent is formIncidencia, so what i’m doing to find it is:

$('#formIncidencia').find("[id='archivo']");

This works fine but when i’m trying to do:

 $('#formIncidencia').find("[id='archivo']").files[0].size; 

it’s not working like that, and i’m uploading a file so don’t know what it’s happening..

Created animation for title and subtitle transform translateY () with css

I am working on a project with vuetify I have created a background image cover over background image I have a title, subtitle and a button.

I should to created same effect animation with css:
Firstly, I should to display title with transform translate Y()
to be coming with animation

Secondly, I should to display subtitle with transform translate Y()
to be coming with animation with the same logic that first, but subtitle should, will be coming after title with some seconds.

For button, we don’t need for anyone animation transform translate Y() just to display in the same position after subtitle with same seconds.
I have done until now to create effect animation for all three element display together, I am sharing my code:

.slide-fade-1-enter-active {
    transition: all .7s ease-out;
}
.slide-fade-1-enter {
    transform: translateY(200px);
    opacity: 0;
}

.slide-fade-2-enter-active {
    transition: all 1s ease-out;
}
.slide-fade-2-enter {
    transform: translateY(200px);
    opacity: 0;
}

.slide-fade-3-enter-active, .slide-fade-3-leave-active {
    transition: opacity 1s;
}
.slide-fade-3-enter, .slide-fade-3-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
}
    <div class="hero-inner">
        <transition name="slide-fade-1" appear>
            @if ($block->input('title') != '')
                <h1 class="text-white "> {{ $block->input('title') }} </h1>
            @elseif($block->image('title_image'))
                <img class="hero-title-img" src="{!!$block->image('title_image', 'default', ['fm' => null])!!}">
            @endif
        </transition>
        <transition name="slide-fade-2" appear>
            @if ($block->input('subtitle') != '')
                <h3 class="text-white  mt-15"> {{ $block->input('subtitle') }} </h3>
            @endif
        </transition>
        <transition name="slide-fade-3" appear>
            @if ($block->input('cta_label') != '')
                <v-cta link="{!!$block->input('cta_link')!!}" label="{!!$block->input('cta_label')!!}"></v-cta>
            @endif
        </transition>
    </div>

But we want to  create exactly  affect animation transform translate  by UI/UX design in the Figma. enter link description here

Nodejs + Mysql, How do I find a name if already exist before inserting the name?

Hi I’m learning nodejs with mysql. I have crated a method to post a name in database. But now I want to execute another method which first check if name does not exist then run post name method

NOTE My table only containes ‘nick_names’ column

Here is my route in router file router.post(‘/’, NickNamesController.createName)

Actual result-> I can post names here: Controller.js

exports.createName = (req, res) => {
  const reqData = new NickNamesModel(req.body);
  NickNamesModel.addNewName(reqData , (err, name) => {
            if (err){
                return res.status(400).send(err.code);
            }
            res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
        });
  
}

Expected: Controller.js Please have a look here This is what I want to achieve

exports.createName = (req, res) => {
  const reqData = new NickNamesModel(req.body);

// first check if name exist or not?
  const ifExist = NickNamesModel.getNameIfExist(reqData.nick_name, (err, name) => {
       if(err){
           return err.code;
        }
      return name;
})

// checking if ifExist has 1 then value already exist. If 0 then not exist
  if(ifExist != 0) {
    return res.status(400).send({success: false, message: Duplicate Name});
} else {
  NickNamesModel.addNewName(reqData , (err, name) => {
            if (err){
                return res.status(400).send(err.code);
            }
            res.status(201).send({success: true, message: 'Name has been inserted successfully', data: name});
        });
  }
  
}

NickNamesModel.js

NickNamesModel.addNewName = (reqData, result) => {
    dbConn.query('INSERT INTO nick_name_table SET ? ', reqData, (err, res) => {
        if (err) {
            console.log('Error while inserting name', err);
            result(err, null);
        }else {
            console.log('Name inserted successfully');
            result(null, res);
        }
    })
}

// Method to check if nick name already exist then return 1 else 0
NickNamesModel.getNameIfExist = (nick_name, result) => {
    dbConn.query('SELECT EXISTS('SELECT station_name FROM stations SET WHERE station_name=? LIMIT 1)', nick_name, (err, res) => {
        if (err){
            console.log('Error while fetching stations', err);
            result(null, err);
        } else {
            console.log('Stations fetched successfully');
            result(null, res)
        }
    })
}

Uncaught SyntaxError: Unexpected token u in JSON at position 0 while fetching data from localstorage [duplicate]

I’m new to react and in this simple ToDo app, I’m trying to fetch notes from localStorage and if they exist, assign it to react notes initial state. Here is the code:

import React, {useState, useEffect}   from 'react';
import ReactDOM from 'react-dom';


 
 const NoteApp = () => {
   const notesData = JSON.parse(localStorage.getItem('notes'));
   const [notes, setNotes ] = useState(notesData || []);
   const [title, setTitle] = useState('');
   const [body, setBody] = useState('');

   const addNote = (e) => {
     e.preventDefault();
    const note =  {
      id:Math.random(),  
      title: title,
       body: body}

     setNotes([...notes, note]);
     setTitle('');
     setBody('');
   }

   const removeNote = (title) => {
     setNotes(notes.filter(note=> (note.title !== title) ));
   }
   useEffect(()=> {    
   localStorage.setItem('notes', JSON.stringify(notes))
  });
  

   return ( 
     <div>
      <h1>Notes </h1>
      {notes && notes.map((note) => (
        <div key={note.id}>
          <h3>{note.title}  </h3>
          <p>{note.body}</p>
          <button onClick={()=> removeNote(note.title)}>x</button> <br />
        </div>
      ))}
 
     <form  onSubmit={addNote}>
       <input type="text" value={title} onChange={e => setTitle(e.target.value)} /><br /> <br /> 
       <textarea value={body} name="body" id="" cols="30" rows="10" onChange={e => setBody(e.target.value)}></textarea>
       <br /><br />
 
       <button>add note</button>
     </form>     
     </div>
    );
 }

 
ReactDOM.render(
  <React.StrictMode>
    <div>
      <NoteApp />
    </div>
  </React.StrictMode>,
  document.getElementById('root')
);

However I get a blank page and this massive error:

VM19427:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at NoteApp (index.js:7:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
NoteApp @ index.js:7
renderWithHooks @ react-dom.development.js:14985
mountIndeterminateComponent @ react-dom.development.js:17811
beginWork @ react-dom.development.js:19049
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
react-dom.development.js:20085 The above error occurred in the <NoteApp> component:

    at NoteApp (http://localhost:3000/static/js/bundle.js:28:26)
    at div

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
update.callback @ react-dom.development.js:20118
callCallback @ react-dom.development.js:12318
commitUpdateQueue @ react-dom.development.js:12339
commitLifeCycles @ react-dom.development.js:20736
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
react-dom.development.js:4005 Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4005:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)
    at renderRootSync (react-dom.development.js:22670:1)
    at performSyncWorkOnRoot (react-dom.development.js:22293:1)
    at scheduleUpdateOnFiber (react-dom.development.js:21881:1)
    at updateContainer (react-dom.development.js:25482:1)
    at react-dom.development.js:26021:1
invokeGuardedCallbackDev @ react-dom.development.js:4005
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:65
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7