Cannot properly update frontend on rerender reactjs using useEffect

So I was making a blog application where only logged in users can add new blogs. To start, when a user logs in, they will see all the blogs they have previously created on the frontend along with a form to add new ones. However, when the logged in user tries to add a new blog, it updates on the frontend but returns back to the original list they had before when the page is refreshed. I can see the updated blog list when I log out and log back in again. I actually used local storage to make sure that logged in users remain logged in after a new render. I just need help in making sure the new blogs added after login remain on the frontend after a render. Any help would be greatly appreciated.

ReactJS code

import { useState, useEffect } from 'react'
import Blog from './components/Blog'
import blogService from './services/blogs'
import loginService from './services/login'
import userService from './services/user'

const App = () => {
  const [blogs, setBlogs] = useState([])
  const [newBlogs, setNewBlogs] = useState([])
  const [user, setUser] = useState(null)
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [errorMsg, setErrorMsg] = useState('')

  const [blogTitle, setBlogTitle] = useState('')
  const [blogAuthor, setBlogAuthor] = useState('')
  const [blogUrl, setBlogUrl] = useState('')

  useEffect( () => {
    if(user != null){
      setBlogs(user.blog.concat(newBlog))
    }
    console.log("blogs is", blogs)
  }, [user])


//Seeing if a user is logged in on rerender

  useEffect(() => {
    const loggedInUser = window.localStorage.getItem('loggedBlogUser')
    if(loggedInUser){
      const user = JSON.parse(loggedInUser)
      setUser(user)
    }
  },[])


  
// Logging in users
  const handleLogin = async (event) => {
    event.preventDefault()
    console.log("Logging in,", username, password)
    try {
      const user = await loginService({username, password})
      blogService.setToken(user.token)
      window.localStorage.setItem('loggedBlogUser', JSON.stringify(user))
      setUser(user)
      setUsername('')
      setPassword('')
    }
    catch(error){
      setErrorMsg('Wrong credentials')
      setTimeout(() => {
        setErrorMsg(null)
      },[])
    }
  }

//Logging out users
  const handleLogout = () => {
    window.localStorage.removeItem('loggedBlogUser')
    setUser(null)
    setBlogs([])
  }

//Adding new blogs
  const addNewBlog = async (e) => {
    e.preventDefault()

    console.log("User here is", user)

    try {
      const newBlog = {
        title: blogTitle,
        author: blogAuthor,
        url: blogUrl
      }
      await blogService.createBlog(newBlog)
      setBlogs(blogs.concat(newBlog))
      setNewBlogs(newBlogs.concat(newBlog))
      setBlogTitle('')
      setBlogAuthor('')
      setBlogUrl('')
    }
    catch(error){
      console.log("error adding new blog", error)
    }

    console.log("blogs is", blogs)
  }

  return (
    <div>
      <h2>blogs</h2>
      {user == null && <div className="login-form">
      <form onSubmit={handleLogin}>
      <div className="username-container">
        username
        <input type='text' value={username} onChange={(e) => setUsername(e.target.value)} name='username'/>
      </div>
      <div className="password-container">
        password
        <input type='password' value={password} onChange={(e) => setPassword(e.target.value)} name='password'/>
      </div>
      <button type='submit'>Login</button>
      </form>
      </div>}
      {user != null && <div className="notes">
        <p>{user.name} logged in <button onClick={handleLogout}>logout</button></p>
      </div>}
      {user != null && <div className="addBlog-container">
      <b>create new</b>
      <form onSubmit={addNewBlog}>
        <label>Title:</label><input type="text" value={blogTitle} onChange={(e) => setBlogTitle(e.target.value)} name="blog-title"/>
        <label>Author:</label><input type="text" value={blogAuthor} onChange={(e) => setBlogAuthor(e.target.value)} name="blog-author"/>
        <label>Url:</label><input type="text" value={blogUrl} onChange={(e) => setBlogUrl(e.target.value)} name="blog-url"/>
        <button type='submit'>create blog</button>
      </form>
      </div>}
      {blogs != null && blogs.map(blog =>
        <Blog key={blog.id} blog={blog} />
      )}
    </div>
  )
}

export default App

Uncaught TypeError: database.ref is not a function using vue 3

I’ve spent a good few hours searching around here but nothing wanted to work. I want to use firebase realtime database but whatever I try, I just keep getting errors. The aim of this webapp is to add, edit, view and delete products from a list. This is what I have in the data.js so far. Any help would be appreciated 🙂

import firebase from 'firebase/compat/app';
import store from "./store";
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/database';
import { getFirestore } from "firebase/firestore";
import { initializeApp } from "firebase/app";

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    databaseURL: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};
  
const app = initializeApp(firebaseConfig);
const database = getFirestore();

export default function setListingData() {
    
    database.ref("/listings")
      .get()
      .then(function(snapshot) {
        if (snapshot.exists()) {
          let listings = [];
          snapshot.forEach((e) => {
            listings.push(e.val());
          });
          console.log(listings);
  
          store.commit("initListings", listings);
  
          return snapshot.val();
        } else {
          console.log("No data available");
        }
      })
      .catch(function(error) {
        console.error(error);
      });
  }
  
  export function deleteListing(id) {
    firebase
      .database()
      .ref(`/listings/${id}`)
      .remove();
  }
  
  /**
   * Add/edit listing
   * @param {*} listing The listing
   */
  export function addListing(listing) {
    console.log("ADDING:", listing);
    firebase
      .database()
      .ref(`/listings/${listings.id}`)
      .set(listings);
  }
  
  export function emptyListing() {
    return {
      title: "",
      price: "",
      description: ""
    };
  }

How to Deal with JavaScript Closure when Using Async Code from a Separate Function

I’m trying to create a cleanup function for my useEffect and update the variable cancelRequest that is being used by the code from my getAllTweets() function.

let cancelRequest = false;

useEffect(() => {
    if (!url) {
        dispatch({ type: "IDLE" });
        return;
    }

    getAllTweets();

    return function cleanup() {
        cancelRequest = true;
    };
}, [state.page]);

...

function getAllTweets() {
    axiosConfig
        .get(`${url}?page=${state.page}`)
        .then((response) => {
            if (cancelRequest) {
                dispatch({ type: "IDLE" });
                return;
            } else if (state.page !== -1) {
                state.page === 1
                    ? dispatch({ type: "LOADED", payload: response.data.data })
                    : dispatch({
                            type: "LOADED",
                            payload: [...state.tweets, ...response.data.data],
                      });
            }

            ...
        })

        ...
}

But I think the variable wasn’t being updated as I’m still getting the Can't perform a React state update on an unmounted component warning on my app when I’m trying to exit while it was fetching data.

Does TypeScript support export default Enum?

I have an enum object which I want to make the export default at the top level like that :

export default enum Hashes{

FOO = 'foo',
BAR = 'bar',
}

I got this error :

Module parse failed: Unexpected token (1:15) File was processed with
these loaders: [02:54] MABROUK, Sahnoun (external – Project)

  • ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
  • ./node_modules/@ngtools/webpack/src/ivy/index.js

I tried this way :

export enum Hashes{
    
    FOO = 'foo',
    BAR = 'bar',
    }

and it seems work only if I import Hashes as alias in all my components like that :

import {Hashes} from … which is a huge change in my project !

any solution ?

Use returned object outside of an async function [duplicate]

I have the following function that gets a survey from Qualtrics:

const fetchQualtricsSurvey = async () => {
    const token = await getAccessToken();
    const progress = await startResponseExport(token);
    const fileId = await getResponseExportProgress(token, progress);
    const survey = await getResponseExportFile(token, fileId);
    console.log(survey);
};

fetchQualtricsSurvey();

It’s currently logging the survey to the console. However, I want to use the JSON that I get in other parts (e.g., visualizing the data using other libraries).

Everytime I try to create a global variable that holds survey I get a promise pending.

Here is the getResponseExportFile function for reference:

async function getResponseExportFile(accessToken, fileId) {
    try {
        const res = await axios(
            `${baseUrl}/API/v3/surveys/${surveyId}/export-responses/${fileId}/file`,
            {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            }
        );
        return res.data.responses;
    } catch (err) {
        console.log(err);
    }
}

How on earth do I use survey outside of this whole async function? Is it even possible? I need to access properties of survey object and use them as values somewhere else.

How could i camelCase a string using .replace method?

I am taking a JS course and my homework was to make a little program that camelCases values from ‘textarea’ input.

Dummy input:

underscore_case
 first_name
Some_Variable
  calculate_AGE
delayed_departure

My code looks something like this:

document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));


document.querySelector('button').addEventListener('click', function () {
  const text = document.querySelector('textarea').value; //Storing data in a variable
  const letsLower = text.toLowerCase(); //Lowecasing
  const arrayedValues = letsLower.split('n');
  let camelCased = [];        //I created an emtpy array so i could changed values to it
  for (let v of arrayedValues) {
    v = v.trimStart();
    const up = v.indexOf('_') + 1; //Here i am detecting the character that should be changed
    v = v.replace(v[up], v[up].toUpperCase()); //replacing lower to upper character
    v = v.replace('_', ''); **deleting the underscore**

    camelCased.push(v); //pushing the changed element to the array
  }
  let emoji = '';
  for (let z of camelCased) {
    emoji += '✔️';
    console.log(`${z} ${emoji}`);
  }
});

Please ignore the check emoji, this was also part of exercise.

So it works untill there is a string that has the character i want to replace earlier in the string, then it just replaces the first instance. (e.g. a_a will be Aa instead of aA)
I know that .replace() method replaces only the first occurrence and this the explanation of the problem.

My question is how could i re-write the program using replace method?
I already know how to solve this problem in another way, as was explained in the course, but i am really corious if it can work this way.

This is not in any way urgent and thanks for your time!

Scheduling daily task with node-cron not working

I’m trying to create an api that returns a random song of the day. I’m trying to schedule the randomize function to run once a day to pick a new song for that day. I’m using node-cron to do this. This function is running way more than once a day, however. It appears to be running more like once an hour, but I’m not certain how often its running. The api is hosted on Heroku if that makes any difference.

const cron = require('node-cron');

let usedSongs = [];
let use;

function randomize() {
    if(usedSongs.length === 169) {
        usedSongs = [];
    };
    let test = Math.round(Math.random(0,1) * 169);
    usedSongs.includes(test) ? randomize() : use = String(test);
    usedSongs.push(test)
};
randomize();

cron.schedule('0 0 0 * * *', () => {
    randomize();
}, {scheduled: true,
    timezone: 'America/New_York'
});

Cannot run PHP function in JavaScript

I’m trying to use setAttribute method of JavaScript on the h1 element .elm.

I got a PHP function and I wanna set the attribute value by this PHP function.

I’m trying the answer here https://stackoverflow.com/a/15757818/19278198 (I don’t want to use Ajax because I haven’t learn that and it’s complicated to me so far)

But this seems not working? Please help.

<?php

function add_value($first, $second) {
  $total = $first + $second;
  
  echo $total;
}

?>

<h1 class="elm"></h1>

<script type="text/javascript">

const text = document.querySelector('.elm');
text.setAttribute('data', <?php echo add_value(1, 2); ?> );
console.log(text);

</script>

replace js confirm with html dialog black box

I’m trying to code js for an html dialog which works with variables so it is reusable and I don’t have to write the same redundant code each time I create a dialog. If user click “OK” then foo = true, and if user click “CANCEL” then foo = false. I want to asign a function name to a js variable (“run_me_true”) and another variable (“run_me_false”) both based on whether foo is true or false. And then run that function contained in the “run_me” variable(s).

// MAIN FUNCTION
function clear_data() { foo = false;
glass = 'ERASE the current player list?';
document.getElementById('show_confirm').innerHTML = glass;

run_me_true = "function do_this ();";
run_me_false = "function do_that ();";

openCONFIRM(); 
}

function foo_status_yes () {foo = true; run_me_true}
function foo_status_no () {foo = false; run_me_false}

// OPEN AND CLOSE DIALOG

function openCONFIRM() { 
 var dialogCONFIRM_O = document.getElementById("confirm_me");
  dialogCONFIRM_O.showModal();
 }

 function closeCONFIRM() {
 var dialogCONFIRM_C = document.getElementById("confirm_me");
 dialogCONFIRM_C.close();
 }

<!-- CONFIRM DIALOG -->
<div>
<dialog id="confirm_me">
<h3 id = "show_confirm"></h3>

<div>
 <button onclick="foo_status_yes();">OK</button>
 <button onclick="foo_status_no();">CANCEL</button>
</div>

</dialog></div>
<!-- END CONFIRM DIALOG-->

How can I compare the current time with my div’s ID (9:00) in javascript?

I understand how to get the current time with moment, now im just trying to compare the time with my div’s ID. my div Ids are times In the format H:MM

HTML:

<div id="11:00" class="row time-div">

what I have so far Javascript:

//checking if the time slot is in the past present or future
//add classes to change style accordingly
$(".time-div").each(function () {

    var timeDiv = $(this).attr("id").val();

    if (currentHour == timeDiv) {
      $(this).addClass("present");

    } else if (currentHour < timeDiv) {
      $(this).removeClass("present");
      $(this).addClass("future");

    } else if (currentHour > timeDiv) {
      $(this).removeClass("future");
      $(this).addClass("past");
    }
});

how can I grab the approvedBy Id in this array?

I am trying to grab the approvedBy Id number in the array shown in the picture below. The picture is being shown in the console by the console.log(visibleAwards) before the return statement. I have to replace the {formatName(award.createdBy)} with the approvedBy object. Can anyone help me? I am having a really hard time knowing where to begin and how to grab it?

import * as React from 'react'
import moment from 'moment'
import { Section } from '../../components/Section'
import EmptyText from '../../components/EmptyText'
import AwardPlaceholder from '../../../assets/images/placeholders/award.png'
import './AwardsSection.scss'
import { nameAndRankFormatterById } from 'app/utils/fullNameFormatter'

export default (props: {
    awards: CopFund.ExpandedAwardType[]
    notStripped?: boolean
}) => {
    const awards = props.awards || []

    const visibleAwards = awards.filter((award) => award.status === 'approved' &&
        (!award.hideUntil || moment(new Date()) >= moment(award.hideUntil)))

    const getAwardImage = (award: CopFund.ExpandedAwardType) => {
        return award.awardTemplateId?.ribbonImagePath || award.awardTemplateId?.medalImagePath || AwardPlaceholder
    }

    const formatName = (user: CopFund.UserType) => {
        return `${user.profile.lastName}, ${user.profile.middleName || ''} ${user.profile.firstName}`
    }

    console.log(visibleAwards);
    return (
        <Section title="Awards" className='mbs-main__section' id='awards-info'>
            {(!awards || awards?.length === 0) && <EmptyText>No award records to show.</EmptyText>}
            {awards?.length > 0 && (
                visibleAwards.map((
                    award: CopFund.ExpandedAwardType,
                    index: number
                ) =>
                    <div className="awards-cards">
                        <div className="award-section-key-card" key={award._id}>
                            <div className="award-section">
                                <h3>Award</h3>
                                <div>{award.name}</div>
                            </div>
                            <div className="submitter-section">
                                <h4>Awarded By</h4>
                                <div>{formatName(award.createdBy)}</div>
                            </div>
                            <div className="date-section">
                                <h5>Date</h5>
                                <div>{moment(award.awardDate).format('MM/DD/yyyy')}</div>
                            </div>
                            <div className="ribbon-section">
                                <div className="ribbon" style={{ backgroundImage: `url("${getAwardImage(award)}")` }}></div>
                                <div></div>
                            </div>
                        </div>
                    </div>)
            )}
        </Section >
    )
}```
[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/F2QxM.png

Find intersection point between a line and a square

I have a line with a point A(starting point) and a point B(finishing point):

a = {x: x, y: y}
b = {x: x, y: y}
line = (a[y] - b[y]) / (a[x] - b[x])

and a rectangle with the center(x,y), width and height:

rectangle = {x: x, y: y, w: w, h: h}

how can I find the intersection between both?

displaying i’th comment only when the i’th value of an array is equal to true in react from firebase

<div class="container card">
        <p>{individualProduct.user_comments.map((eachComment) => (
                <h1 className='comment'> {eachComment} </h1>
        ))}</p>
</div>

By doing this I am simply printing each value in the use_comments array, however, my goal is looping through ucomments_is_approved, and once for example ucomments_is_approved[3] == true then i should show user_comments[3], i have linked below a screenshot of my data base to make it easier, i am new to javascript thus i think its very simple however i was not able to figure it out, any help would be good. Thank you!

FIREBASE DATABASE PICTURE SHOWING THE UCOMMENTS_IS_APPROVED AND USER_COMMENTS