Variable is not defined : Knockout option binding

I am trying to bind an observable array to a dropdown but keep getting message saying “Uncaught (in promise) ReferenceError: Unable to process binding “options: function(){return appointmentStatuses }”
Message: appointmentStatuses is not defined”

var appointmentConfirmationModel = function (rootVM) {
    var self = this;
    
    ////
    ////
    
        self.appointmentStatuses = ko.observableArray([]);
        self.appointmentStatuses.push({ 'key': 'NotConfirmed', 'value': '0' });
        self.appointmentStatuses.push({ 'key': 'Confirmed', 'value': '1' });
        self.appointmentStatuses.push({ 'key': 'Reschedule', 'value': '2' });
        self.appointmentStatuses.push({ 'key': 'Pending', 'value': '3' });
    
    /////
    }
    
    
  

HTML

<div class="appointmentList" data-bind="foreach: visibleAppointments">
        <div class="appointmentListItem">
            <div class="userIcon">
                <img class="" src="~/images/homebuyer-white.png" />
            </div>
            <label class="userName" data-bind="text: name"></label>
            <select data-bind='options: appointmentStatuses, optionsText: ""value"", optionsValue: ""key""'></select>
            <label class="phone" data-bind="text: phone"></label>
            <label class="startTime" data-bind="text: start"></label>
        </div>
    </div>

Error
enter image description here

I cant redirect my users by role type with my app routing component

I have a question regarding roles and route redirection.

Context: My application manages several roles, which can be accessed depending on the login. Such as (Investor, Adviser, Admin), this is handled by the AuthGuard in the app-routing, so that only certain roles that I indicate can enter the views

  {
    path: '',
    redirectTo: 'portal',
    pathMatch: 'full'
  },
  { 
    path: 'portal',
    canActivate: [AuthGuardService], data: { 
      roles: ['adviser', 'investor', 'supervisor']
    },
    loadChildren: () => import('./portal/portal.module').then(m => m.PortalModule)
  },
  { 
    path: 'admin',
    canActivate: [AuthGuardService],
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
  },
  { 
    path: 'adviser',
    canActivate: [AuthGuardService], data: { 
      roles: ['adviser']
    },
    loadChildren: () => import('./adviser/adviser.module').then(m => m.AdviserModule)
  },

So when logging in, knowing what your role is as a user, I redirect to a route and there the route module of each type of user takes care of the other views.

My problem arises because I have this in the app-routing:

  {
    path: '',
    redirectTo: 'portal',
    pathMatch: 'full'
  },

Here I indicate that if the route is empty, redirect it to that main, but that main is for investors, in this case what I want to happen is that if it is Investor, redirect it there, if it is Adviser, redirect it to another and so in all cases, but I do not know how to indicate this.

How to convert base64 to RGBA8888

I’m trying to convert and image to base 64 and then to RGBA8888 to feed camera buffer, i’m stucked when trying to convert from base64 to rgba

function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
  console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}

html part:

<input type="file" onchange="encodeImageFileAsURL(this)" />

React – How to avoid assigning fallback value while loading?

I have a component that renders based on condition.

function MyComponent() {
  return <div>
   {isFruit ? 'Mango' : 'Onion'}
  </div>
}

The problem is that isFruit is fetched from an API, so it’s undefined for some time.

While its undefined, the component renders with Onion (incorrectly), then updates with Mango when isFruit is fetched.

I want to defer the component render if isFruit value is undefined. Is there a way to do that? Or some other way to not show Onion during the API call.

Referencing an object property inside itself

Suppose I have a javascript class like this:

class MyClass {
  foo() {
    // do something
  }

  bar() {
    const baz = this.foo();
    // do something with baz
  }
}

In the bar() function I can call the foo() function using this.

Is it possible to do this using an object instead of a class? For example:

const myObj = {
  foo: () => {
    // do something
  },
  bar: () => {
    const baz = foo(); // this doesn't work
    // do something with baz
  }
}

A solution I found is to define foo and bar outside of the object and then assign them to the object afterwards, but it doesn’t feel right:

const foo = () => {
  // do something
};
const bar = () => {
  const baz = foo();
  // do something with baz
};
const myObj = { foo, bar };

Is there a way to reference an object’s own property from inside of the object?

getting CORS error with json-server while trying to use patch method in axios

I’m making a fake list of messages using react and json-server.I’ve installed json-server using npm and then just created a db.json file and tried to get data from this fake server. everything is good with get and post method but when I’m trying to use patch method I get CORS error :

Access to XMLHttpRequest at ‘http://localhost:3001/data/1’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.

this is the code that I’ve wrote to send api call :

       const sendPost = (data)=> async(dispatch) =>{
       const body = {"answers" : []}
         return  await axios.patch("http://localhost:3001/data/1" , body)
         .then(res => console.log(res))                   
         .catch(err => console.log(err))
         
          }

Jest – How to Test If React Hook Form’s handleSubmit Executes Callback Function Passed

I am writing some unit test but having issues writing a test if the form calls the action function on submit. I am using React Hook Form. Without react hook form the test passes so I believe it has something to do with React Hook Form. Test for delete passes too.
I created a quick example of the code below.
I wrapped the expect for Edit test in waitFor and now I’m getting this error that Actions must be plain objects. Before I did this I was just getting the error “Expected mock function to have been called, but it was not called.”
Can someone please advise?

ReduxForm:

import React, { useState, useEffect } from 'react';
import { Button} from '@mui/material';
import styled from 'styled-components';
import { connect } from 'react-redux';
import { getPosts, deletePost, editPost } from '../redux/actions';
import { useForm,  useController } from 'react-hook-form';

const ReduxForm = ({posts, getPosts, deletePost, editPost}) => {
  const [postInEdit, setPostInEdit] = useState(false);
  
  useEffect(()=> {
    getPosts();
  }, [])

  const handleDeletePost = async id => {
    const deleteResponse = await deletePost(id);
    if(deleteResponse) {
      getPosts();
    } else {
      console.log('could not delete post');
    }
  }

  const handleEditPost = (post) => {
    setPostInEdit(post.id);
  }

  return (
    <StyledFormContainer data-testid='posts'>
      {
        posts && posts.map(post => (
          <div style={{height: '150px'}} id={post.id} key={post.id}>
           {
              postInEdit === post.id ? (<EditPostForm post={post} editPost={editPost} />) :  (<div data-testid='title'>{post.title}</div>)
           }
            <div style={{height: '50px', marginTop: '20px'}}>
              <Button  variant='contained' name='deletBtn' onClick={() => handleDeletePost(post.id)}>Delete</Button>
              <Button  variant='contained' name='editBtn' onClick={() => handleEditPost(post)}>Edit</Button>
            </div>
          </div>
        ))
      }
    </StyledFormContainer>
  )
}

const EditPostForm = ({post, editPost}) => {
  const { id, title } = post;
  const [postTitle, setPostTitle] = useState(title);
 const {control, handleSubmit } = useForm();

  const handleSavePost = async () => {
    const editResponse = await editPost(id, postTitle);
    if(editResponse) {
      getPosts();
    } else {
      console.log('could not edit post');
    }
  }

  return (
    <form id={`edit-${id}`} onSubmit={handleSubmit(handleSavePost)}>
      <input value={postTitle}  name="title" onChange={(e) => setPostTitle(e.target.value)}   />
      <Button variant='contained' name='saveBtn' type='submit'>Save</Button>
    </form>
  );
}

const StyledFormContainer = styled.div`
  display: flex;
  flex-direction: column;
  max-width: 20rem;
  justify-content: center;
  align-items: center;
`;

const mapStateToProps = (state) => ({
  posts: state.posts.posts
})

const mapDispatchToProps = dispatch => ({
  getPosts: () => dispatch(getPosts()),
  deletePost: (id) => dispatch(deletePost(id)),
  editPost: (id, title) => dispatch(editPost(id, title))
})

export default connect(mapStateToProps, mapDispatchToProps)(ReduxForm);

Actions:

import axios from 'axios';

export const getPosts = 
() => 
  async dipatch => {
    dipatch({ type: 'FETCHING_POSTS' });
    try {
      const postsResponse = await axios.get('https://jsonplaceholder.typicode.com/posts');
      dipatch({type: 'RECEIVED_POSTS', payload: postsResponse.data.slice(0, 10) });
    } catch(e) {
      dipatch({type: 'FAILED_RECEIVING_POSTS' });
    }
}

export const deletePost = 
(id) => {
  return async dipatch => {
    dipatch({ type: 'DELETING_POST' });
    try {
      await axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`);
      dipatch({type: 'POST_DELETED'});
      return { success: true }
    } catch(e) {
      dipatch({type: 'FAILED_DELETING_POST' });
      return { success: false }
    }
  }
}
export const editPost = 
(id, title) => {
  return async dipatch => {
    dipatch({ type: 'UPDATING_POST' });
    try {
      await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {title: title});
      dipatch({type: 'POST_EDITED'});
      return { success: true }
    } catch(e) {
      dipatch({type: 'FAILED_UPDATING_POST' });
      return { success: false }
    }
  }
}

Tests:

import React from 'react'
import {render, act, fireEvent, screen, waitFor} from '@testing-library/react'
import  configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import ReduxForm from '../../containers/ReduxForm';
import { Provider } from 'react-redux';
import * as ActionsModule from '../../redux/actions';

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares);
const store = mockStore({
  posts: {
    posts: [
      { 
        id: 1,
        title: 'test'
      }
    ]
  }
})

describe('Redux Form', () => {
  afterEach(()=>{
    jest.clearAllMocks();
  })
  it('test', () => {
    const {getByTestId, container} = render(<Provider store={store}><ReduxForm /></Provider>);
    expect(getByTestId('title')).toHaveTextContent('test');
  })

  it('deletePost is called when delete button is clicked', () => {
    const deleteSpy = jest.spyOn(ActionsModule, 'deletePost').mockResolvedValue({success: true});
    const {getByTestId, getByText, container} = render(<Provider store={store}><ReduxForm /></Provider>);
    expect(getByTestId('title')).toHaveTextContent('test');
    act(() => {
      fireEvent(
        getByText('Delete'),
        new MouseEvent('click', {
          bubbles: true
        })
      )
    });
    expect(deleteSpy).toHaveBeenCalled();
  })

  it('editPost is called when edit button is clicked', async () => {
    const editSpy = jest.spyOn(ActionsModule, 'editPost').mockResolvedValue({success: true});
    const {getByTestId, getByText, container} = render(<Provider store={store}><ReduxForm /></Provider>);
    expect(getByTestId('title')).toHaveTextContent('test');
    
      fireEvent(
        getByText('Edit'),
        new MouseEvent('click', {
          bubbles: true
        })
      )
 
      fireEvent(
        getByText('Save'),
        new MouseEvent('click', {
          bubbles: true
        })
      )
   
    screen.debug();
    await waitFor(() => expect(editSpy).toHaveBeenCalled());
  })
})

enter image description here

Not able to parse data from node file to angular controller using promise

I am using node.js in backend and trying to pass data from node function and using the url in angular.js controller. My angular.js runs within node server itself.

I can see my data in Promise call, but when running the Get function in angular controller it is not showing any data and also the url is going in pending state.

cert.js

module.exports = {
    get_data: get_data
}

function get_data() {
    var options = {
        url: config.url + "/certs",
        cert: fs.readFileSync(config.crt),
        key: fs.readFileSync(config.key),
        passphrase: config.ca.passphrase,
    };

    return new Promise((resolve, reject) => {
        request.get(options, function(error, response, body) {
            if (!error && response.statusCode === 200) {
                resolve(body);
                console.log(body);    // ============> getting json data over here
            }
            else {
                reject(response.statusCode);
            }
        })
    })

Angular controller :-

$scope.certList = function() {
        $http.get("/api/certs").then(
            function success(response) {
                $scope.List = response.data;
                console.log(response);  //============> nothing
            },
            function error(err) {
                console.log('Error: ' + err);
            }
        );
    }

Where am I going wrong ? Why the API is going in pending state ?

How to remove an element from a Firestore array

When deleting a bank from the database, I need to redraw the screen and delete the card with the bank that I deleted. I wrote a filter function that returns elements that are not equal to the id of the element that was removed, but it does not work. How can it be solved?

function getBanks() {
  db.collection("banks").onSnapshot((snapshot) => {
    let banks = [];
    snapshot.docChanges().forEach((change) => {
      const bank = {
        id: change.doc.id,
        ...change.doc.data(),
      };
      if (change.type === "added") {
        banks.push(bank);
        generateBanks([bank]);
      } else if (change.type === "removed") {
        banks.filter((item) => item.id != bank.id);
        generateBanks([bank]);
      }
    });
  });
}

React, add object to array only if it would not be a duplicate

i want to add a object to my array, only if it not exists in this array. i want to check with the id from the passed object.

i have this code now but if was iterate over the array it is not working anymore.
Can someone help me with my code :

  const [events, setEvents] = useState([]);
  const [eventsInCard, setEventsInCard] = useState([]);

  let newValueInCard = eventsInCard.length;
  function addToCard(event) {
    setEventsInCard([...eventsInCard, event]);
    newValueInCard++;
    setInCard(newValueInCard);
  }```

Svelte select specific data from JSON

I need help accessing specific objects in a JSON file based on a name value in Svelte.

I am using JSON as a data source and am able to pull it into my page and loop through it with each.

The JSON looks like so:


[
    {
      "id": 1,
      "title": "Project 1",
      "body": "Project 1 text"
    },
    {
      "id": 2,
      "title": "Project 2",
      "body": "Project 2 text"
    }
  ]

I access the JSON like this:

<script context="module">
    export const load = async ({ fetch }) => {
        const res = await fetch("https://amarton.github.io/amcom-portfolio-svelte/static/port.json");
        const projects = await res.json();
        return {
            props: {
                projects,
            }
        }
    }
 
</script>

<script>
    export let projects; 
</script>

And then loop through and display it like this:

       {#each projects as project}
            <h2>{project.title}</h2>
            <p>{project.body}</p>
        {/each}

I’d like to be able to access objects based on my assigned ids. For example, how do I grab JUST the object with the id of 2 and display its title and body in my page?

Sorry if this is a very basic question and thanks for much for any help you can provide.

useEffect not triggering dependency if is true?

I props data from one component to anothers example ->

ComponentOne
ComponentTwo
ComponentThree

From componentOne i props data to ComponentThree

ComponentOne:

const [clearInput, setClearInput] = useState(false);

  useEffect(() => { 
    if (activeView) { 
      setClearInput(true);
      switch (activeView) {
        case SIDE_BAR_CONTACT_TABS.ALL:
          // some logic
          break;
        case SIDE_BAR_CONTACT_TABS.RECENT:
          // some logic
          break;
        case SIDE_BAR_CONTACT_TABS.MY_CONTACT:
          // some logic

          break;
        default:
          break;
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeView]); // I AM ALSO ADDED setClearInput , clearInput as dependency but no work

<ComponentTwo clearInput={clearInput} />

ComponentTwo:

<ComponentThree clearInput={clearInput} /> 

And ComponentThree:

useEffect(() => { 
  console.log('clearder input v', clearInput);
}, [clearInput]);

useEffect is triggered only ONE…every next time no work? Why.

I am console.log out of useEffect and I got results, but i want to useEffect trigger only on change data from ComponentOne

retrieve variables inside a request in nodeJs Request [duplicate]

I want to send requests to a server.
I need to use node to run my script.

Actually my requests look like that:

var request = require('request');
var options = {
  'method': 'GET',
  'url': 'https://exempleURL',
  'headers': {
    'Content-Type': 'application/json'
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
  
  variable = JSON.parse(response.body)
  
});

the request works and i can log the variable inside the request.
My problem is that I want to use this variable somewhere else in my program.
I don’t know how to do it or even if it is possible.

Thank you for your help ! 🙂

Amplify Auth server side returning signInUserSession:null when sign in

so I’m facing an error when I try to use MFA on server side Amplify, I’m always get this error “User is not authenticated”, I noticed that it’s because when I’m using the function Auth.signIn(name, password, { _id, roles, organizations });, is returning an object but the key signInUserSession is null, but the key Session is not, and that’s why when I call the method Auth.setupTOTP(user); is returning this error.
So let me show you how is the config of the amplify auth:

Auth.configure({
  region: this.authConfig.region,
  userPoolId: this.authConfig.userPoolId,
  userPoolWebClientId: this.authConfig.clientId,
  storage: NodeLocalStorage,
  oauth: {},
});

Difficult to say, I’m not sure if there’s a missing config inside AWS cognito, or a bug from amplify or wtf is going on, haha thanks so much for your help