How to set a default value in a Vue.js props with a Typescript Interface?

In my component in Vue.js, I have a props which is typed with an Interface Typescript, I would like that one of the values contained in my interface has a default value in my props. How can I do that ?

interface User{
    email: string,
    age: number,
    availability: string  // I would like the default value in my props to be "available".
}

export default {
    props: Object as () => User;
}

Thanks

Catch error and put inside a component React

i have an issue this issue is take an error from my try catch and pass this message error to my custom alert component.

bellow is my code:

 export const Register = () => { 

   const dispatch = useDispatch(); 
   
   const [openError, setOpenError] = useState(false);

   const AlertError = openError ? (
    <Dialog open={openError}>
      <AlertCard
        open={openError}
        handleClose={handleCloseError}
        borderTop="1vh solid red"
        color="black"
        severity="error"
        title="Cadastro falhou"
        description='message' //put here message error
      />
    </Dialog>
  ) : (
    ""
  );

const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
      first_name: "",
      last_name: "",
      confirmPassword: "",
      newsletter: "",
    },
    validationSchema: validationSchema,
    onSubmit: async (values) => {
      setIsLoading(true)
      dispatch(signupUserPending());
      dispatch(requestConfirmEmailPending());
      try {
        if (document.getElementById("checkbox").checked) {
          values.newsletter = "on";
        }
        const singUpRes = await signup(values);
        dispatch(signupUserSuccess(singUpRes));
        dispatch(getUserSuccess(singUpRes));
        dispatch(getTokenSuccess(singUpRes));

        const confirmEmailRes = await requestConfirmEmail(singUpRes.user.email);
        dispatch(requestConfirmEmailSuccess(confirmEmailRes));
        setOpenSuccess(true);
        navigate("/confirm-token");

      } catch (err) {
        console.log(err.message); //need take this message error
        dispatch(signupUserFailure(err));
        dispatch(requestConfirmEmailFailure(err));
        setIsLoading(false);
        setOpenError(true);
      }
    },
  });

return (
{AlertError}
...rest of code)
} 

i need catch a message error who come from backend and put this error inside my props description on my custom alert error. But i don`t know how make this i tried make this for some hours.

How can i tweet a random image from a folder every day?

Hello i’m actually trying to make a bot which tweet a random pic everyday (Kinda like @Raccoonhourly)

But i just dont understand how to pick a random image and make the bot tweet it

here’s what i got so far

 const rwClient = require("./twitterClient.js")

const tweet = async () => {
    try {
        await rwClient.v1.tweet("@Onikaplaa jle pompe")
    } catch (e) {
        console.error(e)
    }
}

tweet()

Next.js – TypeError: Cannot read properties of null (reading ‘useMemo’)

Since refactoring my code to move generic hooks and components to their own git submodules within my project I get TypeError: Cannot read properties of null (reading 'useMemo') whenever I call one of my hooks.

I removed all the logic from the hook to make sure it didn’t come from undefined arguments, so now it looks like:

import { useMemo } from 'react'

export function useMap(collection, map, deps = []) {
    return useMemo(() => [], [])
}

I’m using next.js at the lastest version and
the project structure is like this:

  • components/
    • component.js (this is where I call useMap imported from ‘generics’)
  • hooks/
  • pages/
    • index.js (returns component)
  • generics/
    • index.js (with export * from './hooks/useMap')
    • hooks/
      • useMap.js

I also have a jsconfig.json file with the following content, so I can write stuff like import Component from 'components/component':

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

Is next.js not compiling code in my generics folder?

How will I chose many objects with mongoose

For example, I have

[
  { name: "John" },
  { name: "Mike" },
  { name: "Homer" },
  { name: "Bart" },
  { name: "Dmitry" },
  { name: "Dan" }
]

How will I chose many objects with mongoose, if I use .limit(2) I will get [{ name: "John" }, { name: "Mike" }], I need to choose [{ name: "Bart" }, { name: "Dmitry" }]. In default JS this method looks like .slice(3,5). How will I do it with mongoose?

NuxtJS Auth redirects before second API call

when I run the following method on my login page, I get some weird behaviour. After the login() method is called, I want to then run a separate call to fetch profile details & permissions, then redirect to /home, but instead it redirects straight to /, before the second api call has been returned:

attempt() {
      try {
        let data = {
          email: this.creds.email,
          password: this.creds.password
        }

        this.$auth.login({data: data}).then(() => {
          //I want this API call to run BEFORE redirecting
          this.axios.get(this.makeAuthUrl('user/'+process.env.NUXT_ENV_COMMUNITY_ID), this.getHeaders(false)).then(user => {
            console.log(user.data)
            this.$store.commit("SET_PROFILE", user.data.profile)
            this.$store.commit("SET_ABILITIES", user.data.abilities)
            this.actionLoading = false;
            this.$router.push({path: "/home"})
          })
        })

      } catch (e) {
        console.log(e)
        this.actionLoading = false;
        this.$toast.error("Invalid Credentials!");
      }
    }

So how can I modify the code in order to delay the redirect until I explicitly redirect the user?

Using nuxtjs/auth module

Thanks!

Context returns undefined functions on any refresh in React Native App

I have an issue on any app refresh, ONE of my Contexts is returning undefined functions.

I have the following structure:

export default function AppWrapper() {
    return (
        <GlobalProvider>
            <ChildProvider>
                <App />
            </ChildProvider>
        </GlobalProvider>
    );
}

I am getting undefined on functions from ChildProvider, which looks like this:

const INITIAL_STATE = {
    orders: [],
    error: null,
};

const ChildContext = React.createContext({ ...INITIAL_STATE });
const ChildConsumer = ChildContext.Consumer;

const OrderProvider = (props) => {
    const { children } = props;
    const { store, userId } = useContext(GlobalContext);

    const [state, setState] = React.useReducer((state, newState) => {
        const combinedState = { ...state, ...newState };
        return combinedState;
    }, INITIAL_STATE);

    const getDataFromStore = async () => {
        if (store?.id) {
            try {
                const { error, data } = await getOrdersByStore({store.id});
                if (data) {
                    const data1 = <iterating through data>;

                    await setState({ orders: data1 });
                } else {
                    await setState({ error: error });
                }
            } catch (e) {
                await setState({ error: e });
            }
        }
    };

  
    const actions = { getDataFromStore};
    return <ChildContext.Provider value={{ ...state, ...actions }}>{children}</ChildContext.Provider>;
};

export { ChildContext, ChildConsumer, ChildProvider };


And in Home.js, I call these functions as such:

const { getDataFromStore } = useContext(ChildContext)

useEffect(() => {

        const getOrders = async () => {
            store?.name && (await getDataFromStore());
        };
        getOrders();
    }, [store]);

And in Home.js is where that function (and any function defined in ChildContext) is undefined on any refresh.

Some Details:

  • It is not a spelling error, or ‘can’t find file’ error.
  • The only thing I am currently storing in session is the auth token.
  • Everything from state is defined (even if in its INITIAL_STATE form)
  • Wherever I call the undefined function, I use async/await
  • The AppWrapper, GlobalContext and ChildContext are all nested inside a context folder. App.js is in the root directory.

Separating HTML, CSS, and JS causes CSS transition to break

Here’s the singlefile version that works correctly:

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>someColor? CSS+JS poem.</title>
  <link rel="stylesheet" href="./style.css">
</head>
<body>
<body>
  <main class="panels">
    <div class="panel panel1">
      <p>Are</p>
      <p>We</p>
      <p>Ready?</p>
    </div>
    <div class="panel panel2">
      <p>I</p>
      <p>Had</p>
      <p>Thought.</p>
    </div>
    <div class="panel panel3">
      <p>Flap</p>
      <p>Left</p>
      <p>, Then Right.</p>
    </div>
    <div class="panel panel4">
      <p>Take</p>
      <p>The</p>
      <p>Leap.</p>
    </div>
    <div class="panel panel5">
      <p>The</p>
      <p>Ground</p>
      <p>, a Memory...</p>
    </div>
  </main>
</body>
  <script>let panels = document.querySelectorAll(".panel");
    function toggleOpen() {
      this.classList.toggle("open");
    }
    function toggleActive(e) {
      if (e.propertyName.includes("flex")) {
        this.classList.toggle("open-active");
      }
    }
    panels.forEach((panel) => panel.addEventListener("click", toggleOpen));
    panels.forEach((panel) =>
      panel.addEventListener("transitionend", toggleActive)
    );</script>
</body>
</html>
<style>
html {
  background-color: black;
  box-sizing: border-box;
  font-size: 0.6em;
  font-weight: 200;
}
body {
  cursor: pointer;
  margin: 0;
}
*,
:after,
:before {
  box-sizing: inherit;
}
.panels {
  min-height: 99vh;
  overflow: hidden;
  display: flex;
}
.panel {
  box-shadow: inset 0 0 0 8px rgba(255, 255, 255, 0.11);
  color: white;
  text-align: center;
  align-items: center;
  transition: font-size 0.6s cubic-bezier(0.4, -0.1, 0.6, -0.1),
    flex 0.6s cubic-bezier(0.4, -0.1, 0.6, -0.1), background 0.4s;
  background-size: cover;
  background-position: center;
  flex: 4;
  justify-content: center;
  display: flex;
  flex-direction: column;
}
.panel1 {
  background-image: url(https://cdn.pixabay.com/photo/2017/01/28/02/24/japan-2014618_960_720.jpg);
}
.panel2 {
  background-image: url(https://cdn.pixabay.com/photo/2020/01/30/21/24/shop-4806610_960_720.jpg);
}
.panel3 {
  background-image: url(https://cdn.pixabay.com/photo/2020/06/17/17/07/downtown-5310440_960_720.jpg);
}
.panel4 {
  background-image: url(https://cdn.pixabay.com/photo/2017/01/28/02/24/japan-2014617_960_720.jpg);
}
.panel5 {
  background-image: url(https://cdn.pixabay.com/photo/2017/01/28/02/24/japan-2014619_960_720.jpg);
}
.panel > * {
  margin: 0;
  width: 99%;
  transition: transform 0.4s;
  flex: 1 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
.panel > :first-child {
  transform: translateY(-99%);
}
.panel.open-active > :first-child {
  transform: translateY(0);
}
.panel > :last-child {
  transform: translateY(99%);
}
.panel.open-active > :last-child {
  transform: translateY(0);
}
.panel p {
  text-transform: uppercase;
  text-shadow: 0 0 8px rgba(0, 0, 0, 0.68), 0 0 18px rgba(0, 0, 0, 0.48);
  font-size: 2em;
}
.panel p:nth-child(2) {
  font-size: 4em;
}
.panel.open {
  flex: 7;
  font-size: 2em;
}
@media only screen and (max-width: 600px) {
  .panel p {
    font-size: 1em;
  }
}
</style>

However, when I attempt to separate the CSS and JS into separate files, every browser breaks the CSS transition on first load, causing the text to display before the transition occurs (and, interestingly, making the transition play backward). Here’s what it looks like: broken css

Upon refreshing, the browser seems to cache the files, and then works properly for a while. But everytime I reopen the file in a new browser or the cache resets, the transition breaks on load again.

I would greatly appreciate some advice on solving this. I look like a complete NOOB serving singlefile websites in my github portfolio.

Google App Script – Export Active Sheet Without Sheet Name

I am using the script below to export a sheet as Excel file but the output file name is always Document Name + Sheet Name (“Exported – Report.xlsx”). How can I modify this to only use the sheet name as file name of the exported file (“Report.xlsx”)?

function ExportSheet()
{
  var SheetApp = SpreadsheetApp.getActive(); 
  SheetApp.rename("Exported");
  
  ShtURL = SheetApp.getUrl();
  ShtID = SheetApp.getId();
  ShtGID = SheetApp.getSheetId();
  var url = ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID);
  
  var html = HtmlService.createHtmlOutput('<html><script>'
  +'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
  +'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
  +'if(document.createEvent){'
  +'  var event=document.createEvent("MouseEvents");'
  +'  if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'                          
  +'  event.initEvent("click",true,true); a.dispatchEvent(event);'
  +'}else{ a.click() }'
  +'close();'
  +'</script>'
  // Offer URL as clickable link in case above code fails.
  +'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. <a href="'+url+'" target="_blank" onclick="window.close()">Click here to proceed</a>.</body>'
  +'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
  +'</html>')
  .setWidth( 90 ).setHeight( 1 );
  SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );

  SheetApp.rename("Template");
}

Dropdown inside an IFrame closes when clicked outside the IFrame

I have a main program (some sort of testing control panel) that runs another program in an IFrame. In some sorts, this is similar to Storybook. The reason to have an IFrame is to provide some separation between the program that is tested (which may do what it wants with its DOM) and the host w/ the control panel = buttons & co.

I was surprised to observe that if I have in the IFrame a dropdown, and I click somewhere but OUTSIDE that IFrame => the dropdown closes. So practically the code in the IFrame has reacted to an event that happened in the parent window. (NOTE: the page in the IFrame comes from the same domain).

This is something that I don’t bothers me. Any ideas why this happens and what can I do to avoid this? So I’d like the code in the IFrame to stop receiving/reacting events that correspond to actions that I do outside the IFrame.

Why does changing an array in my application change the array from the mock/test

In my application, I am mocking API calls that come from axios and return data to my application. The objects/arrays that are returned are being modified by the test, but I’m not sure how. The array that gets changed maintains it’s new values between two different tests in the same file.

Here is where the mock happens. This function, mockAxiosFetchRequest happens at the beginning of the test and returns different objects depending on the API call. Somehow, the array mockCustomersArray gets modified and retains the new values between tests

import { mockCustomersArray } from './MockData'
const axios = require('axios');
jest.mock('axios');

export const mockAxiosFetchRequest = () => {
  axios.mockImplementation((data: any) => {
    if (data.url.includes('getCustomers')) {
      return {
        pageContent: mockCustomersArray
      }
    } else if (...) {...}
  }
}

Here is where the data (the mock response from above) is handled in the application

const invokeGetSegments = (): Promise<any> => {
    let segmentList: any = [];
    return getSegments()
      .then(async response => {
        if (response.status === 200) {
          segmentList = response.pageContent; 
          segmentList.unshift(
            { segmentId: 'all-customers', description: 'All Customers' },
          ); // this is the line where the mock object gets modified

          setAllSegments(segmentList);
        }
      })
      .catch(() => {
        console.log('error')
      });
  };

On the line above with unshift, the value also gets shifted onto mockCustomersArray. I’m a little confused how this happens because I wouldn’t think that the mock object returned from the jest mock would be in the scope of the invokeGetSegments function.

If I destructure the array like so segmentList = [...response.pageContent] then it works fine and the mock array isn’t affected.

When I don’t destructure the array and leave it as is in the above code block, I’m not sure how the array that gets returned is changed.

Why ? When i use FBXLoader ,my normal map is Invisible?

I new to THREE.js and I use Github uploaded my project,I have an FBX model that contains a Normal map.Everything looks fine with the Microsoft 3D Viewer like this.enter image description here

But when I import it with three.js, the Normal map doesn’t show, am I missing something?

On the computer it looks like:

enter image description here

and my console.

enter image description here

last , here is the complete code.

<script src="./build/three.js"></script>

<script type="module">
    import * as THREE from './build/three.module.js';
    import { OrbitControls } from './jsm/controls/OrbitControls.js';
    import Stats from './jsm/libs/stats.module.js';
    import { GUI } from './jsm/libs/lil-gui.module.min.js';
    import { OBJLoader } from './Loader/OBJLoader.js';
    import { MTLLoader } from './Loader/MTLLoader.js';
    import { FBXLoader } from './Loader/FBXLoader/FBXLoader.js';


    const scene = new THREE.Scene();

    /*--------camera--------*/
    var camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 2000);
    camera.position.set(0, 40, 20);//camera.position
    camera.lookAt(0, 0, 0);

    /*--------renderer--------*/
    const renderer = new THREE.WebGLRenderer({
        antialias: true,
    });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    renderer.shadowMap.enabled = true;//renderer.shadowMap
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    renderer.toneMapping = THREE.ReinhardToneMapping;

    /*--------background--------*/
    scene.background = new THREE.Color(0xffffff);

    /*--------OrbitControls--------*/
    let controls = new OrbitControls(camera, renderer.domElement);
    controls.enablePan = false;
    controls.maxPolarAngle = Math.PI / 2;
    controls.enableDamping = true;
    // controls.minDistance = 100;
    // controls.maxDistance = 1000;

    //FBX
    let FBX_name = ['group0',];
    let FBX_loader = ['loader0',];
    let FBX_url = [
        './models/2022-5-16/2022-05-16-model.fbx',
    ];

    //FBX
    function FBXimport(object_name, object_loader, object_url) {
        object_loader = new FBXLoader();
        object_loader.load(object_url, function (object) {
            object_loader = new THREE.AnimationMixer(object);
            object.traverse(function (child) {
                if (child.isMesh) {
                    child.castShadow = true;
                    child.receiveShadow = true;
                }
            });
            object.position.set(0, 0, 0);
            object.name = object_name;
            object.children[0].name = object_name;
            object.scale.set(0.01, 0.01, 0.01);
            scene.add(object);
        });
        const group = scene.getObjectByName(object_name);
    }
    
    for (let i = 0; i < FBX_name.length; i++) {
        FBXimport(FBX_name[i], FBX_loader[i], FBX_url[i]);
    }

    const light = new THREE.HemisphereLight(0xffeeb1, 0x080820, 4);
    scene.add(light);

    const directionalLight = new THREE.DirectionalLight(0xffa95c, 5);
    directionalLight.position.set(-50, 50, 50);
    directionalLight.castShadow = true;
    directionalLight.shadow.bias = -0.0001;
    directionalLight.shadow.mapSize.width = 1024 * 4; // default
    directionalLight.shadow.mapSize.height = 1024 * 4; // default
    scene.add(directionalLight);

    const helper = new THREE.DirectionalLightHelper(directionalLight, 5);
    scene.add(helper);

    //onresize 
    window.onresize = function () {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    };

    function animate() {
        controls.update();
        // stats.update();
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
    };
    animate();

</script>

Here are examples if needed https://smile881225.github.io/AskQuestions/

How to define default JavaScript sort callback function?

I’m attempting to create my own sort function (question Async version of sort function in JavaScript). I’ve taken merge sort function from Rosetta Code and make it async:

// based on: https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#JavaScript
async function mergeSort(fn, array) {
    if (array.length <= 1) {
        return array;
    }
    const mid = Math.floor(array.length / 2),
          left = array.slice(0, mid), right = array.slice(mid);
    await mergeSort(fn, left)
    await mergeSort(fn, right)
    let ia = 0, il = 0, ir = 0;
    while (il < left.length && ir < right.length) {
        array[ia++] = (await fn(left[il], right[ir]) <= 0) ? left[il++] : right[ir++];
    }
    while (il < left.length) {
        array[ia++] = left[il++];
    }
    while (ir < right.length) {
        array[ia++] = right[ir++];
    }
    return array;
}

But I’m not sure how I can define default function fn to work the same as in JavaScript.

console.log([1, 2, 3, 10, 11, 100, 20].sort());

What should be the default sorting function to match those in the JavaScript engine?
Should I convert numbers to strings and compare those? What is the proper implementation?

JS – insert values from checkbox to input field [closed]

I must select from a window (done with sweetalert2) a row.

first img

And insert them according to the column in each input of the following image
second

Example:

In the sweetalert window, I select a row with the check, the value of the “banco de origen” column… must go in the second image in the input field “banco de origen”