[Vue warn]: Failed to mount component: template or render function not defined. found in —>

I am having an issue swiper js in my project, we are not using vue-router. we are creating components and the backend will render a path and enable components for pages. here are my dependencies

"dependencies": {
"chart.js": "^3.6.2",
"facebook-login-vuejs": "^2.1.3",
"google-maps-api-loader": "^1.1.1",
"idempotent-babel-polyfill": "^7.0.0",
"jest-junit": "^6.4.0",
"jest-localstorage-mock": "^2.4.0",
"jest-serializer-vue": "^2.0.2",
"lodash": "^4.17.21",
"simple-vue-validator": "^0.16.0",
"sinon": "^7.4.1",
"swiper": "^6.8.4",
"vue": "^2.6.14",
"vue-browser-geolocation": "^1.8.0",
"vue-chartjs": "^3.5.1",
"vue-country-region-select": "^2.0.16",
"vue-google-login": "^2.0.5",
"vue-jest": "^3.0.4",
"vue-loading-overlay": "^3.0.4",
"vue-select": "^3.13.0",
"vue-slick-carousel": "^1.0.6",
"vue-template-compiler": "^2.6.14",
"vue-toasted": "^1.1.28",
"vue2-datepicker": "^3.10.2",
"vuelidate": "^0.7.6",
"vuex": "^3.6.2"
}

can anyone help me to solve this issue I have to use this swiper?

Upload Blob file format in react native

I am trying to upload a Blob using my react native app but unable to do so.

Below code is not working in react native but working fine in web browser:-

const formdata = new FormData();
const content = '<a id="a"><b id="b">hey!</b></a>';
const blob = new Blob([content], { type: "text/xml" });

formdata.append("file", blob);

const requestOptions = {
  method: "POST",
  body: formdata,
  redirect: "follow",
};

fetch("https://some-upload-api-path", requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

What’s the difference in uploading files in react native and web browsers.

useEffect cleanup on ‘imported’ async function

Please don’t consider this a duplicate. I have searched many blogs and stuffs but haven’t reached to the solution.

First of all, my question is ‘how to resolve react state change in unmounted component error, and cancel an async function call that is imported within the useEffect hook?’

I know that you can resolve ‘state changed in an unmounted component‘ error by using clean up function in useEffect. In the cases of async call within useEffect hook, you can do clearTimeout, use cancel token for Axios, create [isMounted] state to flag mounted/unmounted state, and etc. So, at least, I know how to veil the react warning

However, my boss wants not only veiling the warning but also cancelling the async request. Here’s the simplified version of code.

import { fetchFunction } from '../../../somewhereInTheDir';

function Page() {
  const [data, setData] = useState([]);
  const [isMounted, setIsMounted] = useState(true);

  async function fetchData() {
    try {
      const data = await fetchFunction(someUri);

      setData(data);
    } catch (error) {
      console.warn(error);
    }
  }

  useEffect(() => {
    if(isMounted) {
      fetchData(ENDPOINT);
    }
    
    return () => {
      setIsMounted(false);
    }
  })
}

The isMounted state veils the warning. So I am seeing nothin in the console, which is a good sign. But this code does not block/cancel data coming from the endpoint when Page component is unmounted. And you cannot use strategies like putting cancel token in the http header, because fetchFunction is from outside.

ps. my boss said using isMounted state as if it were a JavaScript variable could be an anti-pattern from React, since React state change leads to a re-rendering. Is there a better way to veil the warning without using isMounted state?

Recommended Approach For Building a Dynamic Form Within an Existing .NET MVC Application

I’m working on a .NET 6 MVC project, which requires a form that will allow the user to generate <select> elements on the page with a button click. Each dropdown generated will have the same list of options minus any options already selected through the other dropdowns (so that a user can’t select the same option twice). Moreover, whenever a user selects an option using any of the dropdowns, a list of checkboxes that is specific to the option chosen is rendered below the dropdown.

If this description isn’t totally clear, my main point is simply that the form will need a lot of dynamic elements.

The model that I will pass to the form will already have all the properties that the form will need. So, there will be no need for any asynchronous calls to the server while the user is interacting with it. I want the submission to be a simple POST request to the controller of the bound fields.

So, what is the recommended way of building such a dynamic form within an existing MVC application? I thought of two approaches:

  1. Creating a Blazor component with an EditForm, and including it on the page where the form needs to be displayed: I actually did this already, and the form works as intended. However, I’m having a hard time figuring out a good way of POSTing all the bound data to the MVC controller now (if anyone can lend any tips, I’d appreciate it).
  2. Building the form within a normal MVC view, and using JavaScript for the dynamic parts: The advantage of this approach is that it wouldn’t have to disrupt the MVC’s usual way of submitting form data to the controller. But, I fear that JS code would be far more messy than the Blazor code I already wrote.

I would greatly appreciate any advice regarding the choosing between these two options, or any suggestions about alternative solutions.

d3.js Property ‘name’ does not exist on type ‘Node’

I’m implementing a bubble chart on ReactJS with typescript using d3.js, I get the data, structure as according to what I need and and then pass it as nodes but I get an error that says name does not exist on type node.

I’m using :
“d3”: “3.5.17”,
and
“@types/d3”: “3.5.46”

error

Property 'name' does not exist on type 'Node'.  TS2339

        61 | 
        62 |                 var vis = svg.selectAll("circle").data(nodes, function(d, i) {
      > 63 |                   return d.name + i;
           |                            ^
        64 |                 });
        65 | 
        66 |                 vis

that’s how my data is structured

 let _data = Object.keys(data).map((key) => ({
                name: data[key].name,
                className: data[key].name,
                size: data[key].count,
                img: Rising,
            }))

and that’s the function to generate the d3 chart

(function() {
                let json = _data
                let svg = d3
                  .select(".bubble_chart")
                  .append("svg")
                  /*
                  .attr("width", diameter)
                  .attr("height", diameter);
              */
                  .attr("preserveAspectRatio", "xMinYMin meet")
                  .attr("viewBox", "0 0 600 400")
                  //class to make it responsive
                  .classed("svg-content-responsive", true);
              
                let bubble = d3.layout
                  .pack()
                  .size([600, 400])
                  .value(function(d: any) {
                    return d.size;
                  })
                  .padding(2);
              
                // generate data with calculated layout values
                var nodes = bubble.nodes(json).filter(function(d) {
                  return !d.children;
                }); // filter out the outer bubble
              
                var vis = svg.selectAll("circle").data(nodes, function(d, i) {
                  return d.name + i;
                });
              
                vis
                  .enter()
                  .append("circle")
                  .attr("transform", function(d: any) {
                    return "translate(" + d.x + "," + d.y + ")";
                  })
                  .attr("class", function(d: any) {
                    return d.className;
                  })
                  .attr("r", 0)
                  .transition()
                  .duration(1000)
                  .attr("r", function(d: any) {
                    return d.r;
                  });
              
                vis
                  .enter()
                  .append("svg:image").style('opacity', 0)
                  .attr("transform", (d: any) => "translate(" + d.x + "," + d.y + ")")
                  .attr('x', (d: any) => -(d.r/1.5)/2)
                  .attr('y', (d: any) => -(d.r/1.5)/2)
                  .attr("xlink:href", function(d: any) {
                    return d.img;
                  })
                  .attr("width", (d: any) => d.r / 1.5).transition().duration(1000).style('opacity', 1);
            })();

why javascript function fired more than once?

I have a HTML for select that have onchange call getProductFilter function. the script below

html script that call javascript function

when I select the combo box for the first time it working just fine but after I select it twice and so on, the onchange function fired more than once show at console log like this
console log

why is it fired more than once? any idea?

It is possible to know a cookie expiration date?

It is possible to know when a cookie expires? I have a function that gets a cookie:

function getCookie(cName) {
    const name = cName + "=";
    const cDecoded = decodeURIComponent(document.cookie);
    const cArr = cDecoded .split('; ');
    let res;
    cArr.forEach(val => {
        if (val.indexOf(name) === 0) res = val.substring(name.length);
    })
    return res;
}

But I need to know the expiration date also, not only the value.

Does someone know? I couldn’t find a solution.
Thanks

Firebase Sign In with Github/Twitter/Facebook Not working

I have created 2 web applications using firebase and hosting. I am trying to create buttons that will sign in with Facebook, twitter, GitHub. I have a google button and that works no problem. However, the twitter, Facebook, and GitHub all ask for login info and then nothing happens. The console on Chrome gives no errors.

Here is my HTML code where I am running the scripts

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UFT-8">
    <title>Sawyer Talks | Login</title>
    <meta name="viewport" content="width=device-width; initial-scale=1.0;">
     <!-- Cool Google Fonts -->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@900&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Bowlby+One+SC&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <!-- Our stylesheet -->
    <script src="https://kit.fontawesome.com/550d583bad.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="../login/style.css">
</head>
<body>
    
    <section>  
        <div class="box">  
             <div class="container">  
                  <div class="form">  
                    <h2 class="form_header"> Sawyer Talks | Login </h2>
                       <form>  
                            <div class="input__box">  
                                 <input type="text" placeholder="Email"  id="email">  
                            </div>  
                            <div class="input__box">  
                                 <input type="password" placeholder="Password" id="password">  
                            </div>  
                            <div class="input__box">  

                                 <button type="button" onclick="login()">Login</button> </br>
                                 <!-- <button type="button" onclick="window.location.href='/login/register.html'">Register</button> -->  
                                    </div class="social__logins">  
                                         <button style="justify-content: center;
                                         align-items: center; background-color: rgba(255, 255, 255, 0.589); border-radius: 35px; border: 1px solid rgba(255, 255, 255, 0.5);box-shadow: 0 5px 15px rgb(0 0 0 / 5%); border-right: 1px solid rgba(255, 255, 255, 0.2); border-bottom: 1px solid rgba(255, 255, 255, 0.2); height:30px; padding-left:10px;padding-right:10px; margin-bottom: 20px; margin-top: 20px; margin-right: 10px;" type="button" id="googlesignin" > <i class="fa-brands fa-google"></i> Google</button>
                                         <button style="justify-content: center;
                                         align-items: center;background-color: rgba(255, 255, 255, 0.589); border-radius: 35px; border: 1px solid rgba(255, 255, 255, 0.5);box-shadow: 0 5px 15px rgb(0 0 0 / 5%); border-right: 1px solid rgba(255, 255, 255, 0.2); border-bottom: 1px solid rgba(255, 255, 255, 0.2); height:30px; padding-left:10px;padding-right:10px;margin-right: 10px;" type="button" id="twittersignin"><i class="fa-brands fa-twitter"></i> Twitter</button>
                                         <button style="justify-content: center;
                                         align-items: center;background-color: rgba(255, 255, 255, 0.589); border-radius: 35px; border: 1px solid rgba(255, 255, 255, 0.5);box-shadow: 0 5px 15px rgb(0 0 0 / 5%); border-right: 1px solid rgba(255, 255, 255, 0.2); border-bottom: 1px solid rgba(255, 255, 255, 0.2); height:30px; padding-left:10px;padding-right:10px;margin-bottom: 20px; margin-right: 10px;" type="button" id="githubsignin"><i class="fa-brands fa-github"></i>  Github</button>
                                         <button style="justify-content: center;
                                         align-items: center;background-color: rgba(255, 255, 255, 0.589); border-radius: 35px; border: 1px solid rgba(255, 255, 255, 0.5);box-shadow: 0 5px 15px rgb(0 0 0 / 5%); border-right: 1px solid rgba(255, 255, 255, 0.2); border-bottom: 1px solid rgba(255, 255, 255, 0.2); height:30px; padding-left:10px;padding-right:10px;margin-right: 10px;" type="button" id="facebooksignin"> <i class="fa-brands fa-facebook"></i> Facebook</button>
                                         <button style="justify-content: center;
                                         align-items: center;background-color: rgba(255, 255, 255, 0.589); border-radius: 35px; border: 1px solid rgba(255, 255, 255, 0.5);box-shadow: 0 5px 15px rgb(0 0 0 / 5%); border-right: 1px solid rgba(255, 255, 255, 0.2); border-bottom: 1px solid rgba(255, 255, 255, 0.2); height:30px; padding-left:10px;padding-right:10px;margin-right: 10px;" type="button" id="applesignin"> <i class="fa-brands fa-apple"></i> Apple</button>
                                        <!-- <button type="button" onclick="window.location.href='/login/register.html'">Register</button> -->
                                        <p style="margin-top:20px; color:rgb(73, 73, 73); font-size: small;" class="forget">Don't have an account? <a style="color:rgb(73, 73, 73); font-weight: 600;" href="/login/register.html">Register</a></p>  
                                    </div>  
                            </div> 
                       </form>  
                  </div>  
             </div>  
        </div>  
   </section>  
    
</body>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.8/firebase-database.js"></script>

<!-- Our script must be loaded after firebase references -->
<script src="../login/index.js"></script>
<script type="module">


 import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
 import { getDatabase } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-database.js";
 import { getAuth, onAuthStateChanged, signInWithEmailAndPassword, GoogleAuthProvider, signInWithRedirect, getRedirectResult, signInWithPopup, signOut, GithubAuthProvider, TwitterAuthProvider, FacebookAuthProvider, OAuthProvider } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js"; 
 


     // Your web app's Firebase configuration
     var firebaseConfig = {
        apiKey: "insert_api_key",
        authDomain: "auth.sawyertalks.com",
        databaseURL: "https://sawyer-talks-default-rtdb.firebaseio.com",
        projectId: "sawyer-talks",
        storageBucket: "sawyer-talks.appspot.com",
        messagingSenderId: "364789111427",
        appId: "app_id",
        measurementId: "id_goes_here"
     };
     // Initialize Firebase
     const app = initializeApp(firebaseConfig); 
     const auth = getAuth(app);

     // Login With Google Account 

     const googleProvider = new GoogleAuthProvider(app);

        googlesignin.addEventListener('click',(e) => {
        signInWithPopup(auth, googleProvider)
        .then((result) => {
            // This gives you a Google Access Token. You can use it to access the Google API.
            const credential = GoogleAuthProvider.credentialFromResult(result);
            const token = credential.accessToken;
            // The signed-in user info.
            const user = result.user;


            location.href = '../index.html';
            // ...
            }).catch((error) => {
                // Handle Errors here.
                const errorCode = error.code;
                const errorMessage = error.message;
                // The email of the user's account used.
                const email = error.email;
                // The AuthCredential type that was used.
                const credential = GoogleAuthProvider.credentialFromError(error);
                // ...

                alert(errorMessage);
            });
        });

        // Login with Github Account

        const githubProvider = new GithubAuthProvider(app);
        githubsignin.addEventListener('click',(e) => {
        signInWithRedirect(auth, githubProvider);
        getRedirectResult(auth, githubProvider)
        .then((result) => {
            const credential = GithubAuthProvider.credentialFromResult(result);
            if (credential) {
            // This gives you a GitHub Access Token. You can use it to access the GitHub API.
            const token = credential.accessToken;
            // ...
            }

            // The signed-in user info.
            const user = result.user;
            location.href = '../index.html';
            }).catch((error) => {
                // Handle Errors here.
                const errorCode = error.code;
                const errorMessage = error.message;
                // The email of the user's account used.
                const email = error.email;
                // The AuthCredential type that was used.
                const credential = GithubAuthProvider.credentialFromError(error);
                // ...
            });
        });

        // Login with Twitter Account

        const twitterProvider = new TwitterAuthProvider(app);
        twittersignin.addEventListener('click',(e) => {
        signInWithPopup(auth, twitterProvider)
        .then((result) => {
                // This gives you a the Twitter OAuth 1.0 Access Token and Secret.
                // You can use these server side with your app's credentials to access the Twitter API.
                const credential = TwitterAuthProvider.credentialFromResult(result);
                const token = credential.accessToken;
                const secret = credential.secret;

                // The signed-in user info.
                const user = result.user;
                // ...
                location.href = '../index.html';
            }).catch((error) => {
                // Handle Errors here.
                const errorCode = error.code;
                const errorMessage = error.message;
                // The email of the user's account used.
                const email = error.email;
                // The AuthCredential type that was used.
                const credential = TwitterAuthProvider.credentialFromError(error);
                // ...
            });
        })

        // Login with Facebook Account
        const facebookProvider = new FacebookAuthProvider(app);
        facebookProvider.addScope('email');
        facebooksignin.addEventListener('click',(e) => {
           signInWithPopup(auth, facebookProvider)
           .then((result) => {
           // The signed-in user info.
           // This gives you a Facebook Access Token. You can use it to access the Facebook API.
           const credential = FacebookAuthProvider.credentialFromResult(result);
           const accessToken = credential.accessToken;

           const user = result.user;

           // ...
           location.href = '../index.html';
           })
           .catch((error) => {
           // Handle Errors here.
           const errorCode = error.code;
           const errorMessage = error.message;
           // The email of the user's account used.
           const email = error.email;
           // The AuthCredential type that was used.
           const credential = FacebookAuthProvider.credentialFromError(error);

           // ...
           
           });

      });

      // Login with Apple Account

      const appleProvider = new OAuthProvider('apple.com')
      appleProvider.addScope('email');
      appleProvider.addScope('name');

      applesignin.addEventListener('click',(e) => {
      signInWithPopup(auth, appleProvider)
      .then((result) => {
           // The signed-in user info.

           // Apple credential
           const credential = OAuthProvider.credentialFromResult(result);
           const accessToken = credential.accessToken;
           const idToken = credential.idToken;

           const user = result.user;

           // ...
           location.href = '../index.html';
           })
           .catch((error) => {
           // Handle Errors here.
           const errorCode = error.code;
           const errorMessage = error.message;
           // The email of the user's account used.
           const email = error.email;
           // The credential that was used.
           const credential = OAuthProvider.credentialFromError(error);

           // ...
           });
      });


     </script>

Below is my .js code which runs fine

// Your web app's Firebase configuration
 var firebaseConfig = {
apiKey: "AIzaSyCLSGVG_LsnWpBYCzuVdCFei-I-qf3oODI",
authDomain: "auth.sawyertalks.com",
databaseURL: "https://sawyer-talks-default-rtdb.firebaseio.com",
projectId: "sawyer-talks",
storageBucket: "sawyer-talks.appspot.com",
messagingSenderId: "364789111427",
appId: "1:364789111427:web:9d4125884f8c2cf76599b6",
measurementId: "G-CW4Z3NZZE1"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Initialize variables
const auth = firebase.auth()
const database = firebase.database()

// Set up our register function
function register () {
// Get all our input fields
First_Name = document.getElementById('fname').value
Last_Name = document.getElementById('lname').value
Username = document.getElementById('username').value
email = document.getElementById('email').value
password = document.getElementById('password').value
PhoneNum = document.getElementById('phonenum').value

// Validate input fields
if (validate_email(email) == false || validate_password(password) == false) {
  alert('Please enter a valid email and password.')
  return
  // Don't continue running the code
}
    if (validate_field(Last_Name) == false || validate_field(First_Name) == false ||             validate_field(Username) == false || validate_field(PhoneNum) == false) {
  alert('Please fill out all fields.')
  return
}

// Move on with Auth
auth.createUserWithEmailAndPassword(email, password)
.then(function() {
  // Declare user variable
  var user = auth.currentUser

  // Add this user to Firebase Database
  var database_ref = database.ref()

  // Create User data
  var user_data = {
    email : email,
    First_Name : First_Name,
    Last_Name : Last_Name,
    Username : Username,
    PhoneNum : PhoneNum,
    last_login : Date.now()
  }

  // Push to Firebase Database
  database_ref.child('users/' + user.uid).set(user_data)

  // DOne
  alert('Registration Complete!')
  location.href = '../index.html';
})
.catch(function(error) {
  // Firebase will use this to alert of its errors
  var error_code = error.code
  var error_message = error.message

  alert(error_message)
 })
 }

 // Set up our login function
 function login () {
// Get all our input fields
email = document.getElementById('email').value
password = document.getElementById('password').value

// Validate input fields
if (validate_email(email) == false || validate_password(password) == false) {
  alert('Incorrect email/password.')
  return
  // Don't continue running the code
}

auth.signInWithEmailAndPassword(email, password)
.then(function() {
  // Declare user variable
  var user = auth.currentUser

  // Add this user to Firebase Database
  var database_ref = database.ref()

  // Create User data
  var user_data = {
    last_login : Date.now()
  }

  // Push to Firebase Database
  database_ref.child('users/' + user.uid).update(user_data)

  // DOne
  alert('Logged In!')
  window.location.href="../index.html";
  


})
.catch(function(error) {
  // Firebase will use this to alert of its errors
  var error_code = error.code
  var error_message = error.message

  alert(error_message)
})
 }




 // Validate Functions
  function validate_email(email) {
  expression = /^[^@]+@w+(.w+)+w$/
   if (expression.test(email) == true) {
  // Email is good
  return true
  } else {
  // Email is not good
   return false
  }
  }

function validate_password(password) {
// Firebase only accepts lengths greater than 6
if (password < 6) {
  return false
} else {
  return true
}
}

function validate_field(field) {
if (field == null) {
  return false
}

if (field.length <= 0) {
  return false
} else {
  return true
}
}

Any help would be appreciated. thank you!

Using Flexbox, can I change the amount of items displayed on a row, depending on how many items are added

Scenario:

Using flexbox, I’m creating a template where the number of ‘cards’ displayed can change from page to page. If a user adds 2, 3 or 4 cards – the layout is great.

However, if a user adds 5 cards, the layout is now less aesthetically pleasing with the 5th card alone on a new row.

Is there a way I can display up to 4 cards on a row, but if there are 5+ cards.. then the first row would display 3 cards, and the second row would display 2?

Here’s a general idea of how the code would be displayed.

<style>
.cards-wrapper {
display: flex;
flex-wrap: wrap;
}
.cards-wrapper .card {
flex: 1 1 20%;
margin: 10px;
}
</style>

<div class="cards-wrapper">

    <div class="card"> </div>

    <div class="card"> </div>

    <div class="card"> </div>

    <div class="card"> </div>

    <div class="card"> </div>

</div>

Javascript Quick Sort Algorithm

I’ve been brushing up on some forgotten skills for a interview recently, mainly sorting algorithms, and I’ve come across two different ways to do quick sort and I’m having trouble telling which one is the proper way of doing it. Does anyone know which one is correct?

Version 1:

const quickSort(arr, start, end){
  if (start >= end) {
        return;
  }
    
  let index = partition(arr, start, end);

  quickSort(arr, start, index - 1);
  quickSort(arr, index + 1, end);
}

function partition(arr, start, end){
  const pivotValue = arr[end];
  let pivotIndex = start;

  for (let i = start; i < end; i++) {
    if (arr[i] < pivotValue) {
      [arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];
      pivotIndex++;
    }
  }
   
  [arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]] 
  return pivotIndex;
}

Version 2:

function QuickSort(Arr){
  if(Arr.length < 2) return Arr;

  const pivot = Arr[0];
  const leftArr = [];
  const rightArr = [];

  for(let i = 1; i < Arr.length; i++){
    if(Arr[i] < pivot){
      leftArr.push(Arr[i]);
    }
    else{
      rightArr.push(Arr[i])
    }
  }

  return [...QuickSort(leftArr), pivot, ...QuickSort(rightArr)];
}

How can i add data in Realtime and display in my React app

export default function AllQuestion() {

  let [allQuestion, setAllQuestion] = useState([]);
  let isMounted = true;
  let [userAnswer, setUserAnswer] = useState("");
  const navigate = useNavigate();
  const getData = () => {
    const userId = sessionStorage.getItem("id");
    Services.getAllQuestions(userId).then((res) => {
      if (isMounted) {
        console.log(res.data);
        //-------------------Reference----------------------
        setAllQuestion(res.data);
      }
    });
  };
  useEffect(() => {
    getData();
    return () => {
      isMounted = false;
    };
  }, []);

  const submitAnswerHandler = (qid) => {
    console.log(qid);
    console.log(userAnswer);
    const uid = sessionStorage.getItem("id");
    const name = sessionStorage.getItem("name");
    const dept = sessionStorage.getItem("department");
    const role = sessionStorage.getItem("role");
    const date = new Date();
    const today =
      date.getDay() +
      "/" +
      date.getMonth() +
      "/" +
      date.getFullYear() +
      " at " +
      date.getHours() +
      ":" +
      date.getMinutes();
    const answerObj = {
      userId: uid,
      userName: name,
      userDepartment: dept,
      userRole: role,
      ansDate: today,
      answer: userAnswer,
      quesion_id: qid,
    };
    //------------------Reference----------------------------
    Services.answerQuestion(uid, qid, answerObj).then((res) => {
      toast.success(res.data);
      //---------------Reference------------------------ 
      navigate('/home')
      console.log(res.data);
    });
  };

  return (
    <>
      <Header />
      <LeftContainer />
      <ToastContainer/>
      <div className="right-question-div">
        {//---------------------Reference------------------}
        <Accordion allowZeroExpanded>
          {allQuestion.map((question) => (
            <AccordionItem key={question.id}>
              <Accordion>
                <AccordionItemHeading>
                  <AccordionItemButton>{question.question}</AccordionItemButton>
                </AccordionItemHeading>
                <AccordionItemPanel className="accordion__panel-cstm ">
                  <div className="detail-heading">
                    <u>Asked By</u>
                  </div>
                  <div className="detail">{question.userName}</div>
                  <div className="detail">
                    {question.userRole} - {question.userDepartment}
                  </div>
                  <div className="detail">On {question.quesDate}</div>
                  <hr />
                  <div>
                    {question.answers.map((answer) => (
                      <AccordionItemPanel
                        className="accordion__panel-cstm "
                        key={answer.id}
                      >
                        <div > {answer.answer}</div>

                        <div className="detail-heading">
                          <u>Answerd By</u>
                        </div>
                        <div className="detail">{answer.userName}</div>
                        <div className="detail">
                          {answer.userRole} - {answer.userDepartment}
                        </div>
                        <div className="detail">On {answer.ansDate}</div>
                        <hr />
                        
                        <div></div>
                      </AccordionItemPanel>
                    ))}
                  </div>
                </AccordionItemPanel>
              </Accordion>
              <Accordion className="">
                <AccordionItemHeading className="a-inline-block">
                  <AccordionItemButton className="accordion__button-btn ">
                    Answer This Question
                  </AccordionItemButton>
                </AccordionItemHeading>
                <AccordionItemPanel>
                  <div className="answering-div">
                    <form className="answer-form">
                      <div>
                        {//----------------Reference-----------------}
                        <textarea
                          className="ans-box"
                          onChange={(e) => setUserAnswer(e.target.value)}
                        ></textarea>
                      </div>
                      <div>
                        <button
                          className="ans-btn"
                          value={question.qid}
                          onClick={(e) => {
                            e.preventDefault();
                            submitAnswerHandler(question.id);
                            
                          }}
                        >
                          Answer
                        </button>
                      </div>
                    </form>
                  </div>
                </AccordionItemPanel>
              </Accordion>
            </AccordionItem>
          ))}
        </Accordion>
      </div>

      <Footer />
    </>
  );
}

Here on render of the above component I get all the question stored on the server side . Then I perform nested mapping in order to traverse and display the data . Also I set answers and submit it for the particular questionID . The problem I am facing is that when I post an answer I have to either reload the same component in order to get updated allQuestion array of object or I have to navigate to some other component the come back to this component , even navigating to the same component don’t work.
I just want to Display the answer on real-time without loading the component again before or after sending answerObj to the server.

The structure of allQuestion list of object

   allQuestion=[
    {
    "questionId":qid,
    ....,
    ....,
    ....,
    answers:[
    {
    "answerId":aid,
     .....
     },
     ]
     }]

Applying State to Nested Object in React. How do I call API and display with Use Effect

So I have been re-iterating my code and working around with it for a few hours and I need help. My goal was to use “use-effect” to load an api call from a horoscope API. I ran into this error where I was only able to see the data AFTER I loaded another page from the website and re-rendered the homepage. My goal was to see the data displayed initially on UseEffect() from when I called it. However, it seems to not work. Not sure if I need to use setInitialState, or manipulate the way I am exporting the values through context.

On further speculation,
I somewhat see what the problem is in my code, but I have no idea HOW to use setInitialState to load values in from the api.

          initialState.data.yesterday = data;

? Do i save this to the a variable then call set data on that variable?

1.) I tried manipulating state best I could could.
2.) Page never loads data from API on first run, only shows data after I click a button
3.) Code seems to need setInitialDate but can’t find reasonable solution mixed with use effect to get the data right.

Thank you!!

I am willing to hear all optimal solutions for my problem. I am not even sure if I am going in the right direction. Thanks.


const [initialState, setInitialState] = useState({
    data: {
        yesterday: {},
        today: {},
        tomorrow: {},
    }
});

useEffect(() => {
    console.log("useEffect called");
    // eslint-disable-next-line react-hooks/exhaustive-deps
    async function getDayInfos() {
        try {
            const response = await axios.post('https://aztro.sameerkumar.website/?sign=aries&day=yesterday');
            const data = response.data
            initialState.data.yesterday = data;
        } catch (error) {
            console.error(error);
        }


        try {
            const response = await axios.post('https://aztro.sameerkumar.website/?sign=aries&day=today');
            initialState.data.today = response.data
        } catch (error) {
            console.error(error);
        }

        try {
            const response = await axios.post('https://aztro.sameerkumar.website/?sign=aries&day=tomorrow');
            initialState.data.tomorrow = response.data
        } catch (error) {
            console.error(error);
        }
    }

    getDayInfos()
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

return <AstroContext.Provider value={{initialState}}>
    {children}
</AstroContext.Provider>

}