why answer logs undefined how to set state from use function to another? [duplicate]

I have function1 in one file and function2 in another file. But when i call function1 it logs answer undefined? Why this happens with my code? and when i put both the function in single file that i logs answer hello, world which is expected output?

function1: file1.ts

    const [answer, setAnswer] = useState<string>('');

  const function1 = async () => {
        try {
            const Answer = await function2(setAnswer);
            if (Answer === 'Answered') {
                console.log("prompt is", answer)
const submitAns = await submitAnswer(answer)
return submitAns
            }
        } catch (error) {
            console.log(error)
        }
    }

function2: file2.ts:

export const function2 = async (setAnswer: (value: string) => void) => {
    try {
        const answer = "hello, world"
        setAnswer(answer);
        return 'Answered';
    } catch (error) {
        console.log(error)
    }
};

Pug template won’t render after redirecting to new url

Whenever I attempt to redirect to a new url with query params and then try to render it after, it doesn’t want to render. If i take the additional query params off, the page will render just fine.

These are the functions to check for user logins and their profile that displays afterwards. The function is meant to send in the user’s username into the url and then be grabbed by the profile function to populate the profile pug template.

exports.loginCheck = async (req, res) => {
    let usernameStr = req.body.username;
    let passwordStr = req.body.password;

    var userFound =  await User.findOne()
    .where("username")
    .equals(usernameStr)
    .where("password")
    .equals(passwordStr)
    .select("username email age password answer1 answer2 answer3")
    .then((account) => {
        console.log(userFound);        
        res.redirect(`/profile/${account.username}`);
        
    })
    .catch((err) => {
        console.log(err);
        res.render("login", {
            errorMsg: 'Username and/or password is incorrect.'
            
        });
    });
}



exports.profile = async (req, res) => {
    var param = req.params.userP;

    var userFound =  await User.findOne()
    .where("username")
    .equals(param)
    .select("username email")
    .then((user) => {
        res.render('profile', {
            username: user.username, //I get an error saying cant read '.username', but it will find the user
            email: user.email
        })
    })
    

    

}

The routes:

   app.get('/profile/:userP', routes.profile); //this one doesnt render
   app.get('/profile', routes.profile); //this one does render
   app.post('/profile/login', urlencodedParser, routes.loginCheck); //the post route after users login

All of these routes are meant to render the profile pug template.

I’ve tried doing params, query strings, messing with the form routes that post to the profile page, redirecting and rendering on both the login function and the profile function. I was hoping to post the data to the login function via the ‘/profile/login’ route and then redirect to the profile page with the user’s information or just the username sent to the profile page so I can then fill the profile page with the user’s information from my database.

use context in Qwik

I utilize context in Qwik in the following manner.

import {
    component$,
    Slot,
    useContextProvider,
    useStore,
} from '@builder.io/qwik'
import { AppContext } from 'Base'

const AppContextProvider = component$(() => {
    const app = useStore({
        Qwik: "Qwik context is ready to use",
    })
    useContextProvider(AppContext, [app])

    return (
        <>
            <Slot />
        </>
    )
})

export default AppContextProvider

I utilize it within my components.

const [app] = useContext(AppContext)

then I can change or add new item in store in components like this

app.compareItemsId=[1,2,3,4]

When I try to access this value in other components, its data type shows as “proxy”.
Proxy(Array)
how can I fix this problem
log from context

Install json package in visual studio wiht Terminal

I am learning JS and in a sample project the tutor installed json package with npm init --y i did it in my visual studio Terminal but i got this message:

The term ‘npm’ is not recognized as the name of a cmdlet

the structure of my project is G:final projectRoutesSample
I do not have git on my project.
Thanks for your attention.

React Native @react-native-picker/picker not displaying options

I’m working on a React Native app and using @react-native-picker/picker for a dropdown menu. However, the picker is not displaying any options when clicked. Below is the relevant code snippet from my registration form component

const Registration = () => {
const [user, setUser] = useState({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    mentalHealthHistory: 'None',
    age: '',
    genderOptions: {
      Male: { selected: true, borderColor: 'white' },
      Female: { selected: false, borderColor: '#000' },
      Other: { selected: false, borderColor: '#000' },
    },
    therapyOption: 'Yes',
    contact: '',
  });

  const mentalHealthOptions = ['No Known History', 'Anxiety Disorders', 'Depression', 'Bipolar Disorder', 'Diagnosed PTSD', 'Schizophrenia', 'Substance Abuse', 'Eating Disorder', 'OCD', 'Personality Disorders', 'Self-harm', 'Other'];
  // ... rest of my code

  <Text style={styles.mainInputLabel}>Mental Health History</Text>
  <View style={styles.input}>
    <Picker
      selectedValue={user.mentalHealthHistory}
      onValueChange={(itemValue) =>
        setUser({ ...user, mentalHealthHistory: itemValue })
      }
    >
      {mentalHealthOptions.map((option, index) => (
        <Picker.Item key={index} label={option} value={option} />
      ))}
    </Picker>
  </View>

  // ...rest of my code

};

const styles = StyleSheet.create({
//... rest of my styles
  input: {
    height: 54,
    marginBottom: 12,
    borderWidth: 2,
    borderRadius: 25,
    borderColor: "#4C6880",
    padding: 10,
    marginLeft: 20,
    marginRight: 20,
    backgroundColor: 'white',
  },

});

export default Registration;

I’ve tried the following based on a suggestion to ensure the picker is visible:

<Picker
  selectedValue={user.mentalHealthHistory}
  onValueChange={(itemValue) => setUser({ ...user, mentalHealthHistory: itemValue })}
  style={{ backgroundColor: 'white', zIndex: 1000, elevation: 1000 }}
>
  {/* Picker Items */}
</Picker>

Despite this, the picker options still do not appear when the picker is tapped. I’ve checked that each Picker.Item has a valid label and value. Is there something I’m missing here? How can I get the Picker to properly display the options when interacted with?

calculating the scroll amount for lerp on resize

the scrollable element translate property isn’t responsively matching the window’s right side (doesn’t stick to the right side as if the transform drags the element left and right)when the window is resized if the size is getting smaller there is a blank portion created or when getting bigger scrollable element goes overflow and the scrolling doesn’t work on it.
elements inside scrollable are vw based width and the heights are all 100vh
www.whitemorality.ir

    
        .container-fixed {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            display: flex;
            overflow: hidden;
        }

        .scrollable {
            position: absolute;
            top: 0;
            left: 0;
            display: flex;
            height: 100vh;
            flex-direction: row;
            width: auto;
        }


<body>


    <div class="container-fixed">
        <div class="scrollable">
        
        </div>
    </div>

<script>

window.addEventListener('load', setHeight);
window.addEventListener('resize', setHeight);

            
const scrollable = document.querySelector(".scrollable");

let current = 0;
let target = 0;
let ease = 0.04;

function setHeight() {
let scrollableWidth = scrollable.getBoundingClientRect().width;
let bodyheight = scrollableWidth - (window.innerWidth - window.innerHeight);
document.body.style.height = `${Math.max(0, bodyheight)}px`;

}

function lerp(start, end, amount) { return start * (1 - amount) + end * amount };

function animate() {
target = window.scrollY ;
current = lerp(current, target, ease);
scrollable.style.transform = `translateX(${-current.toFixed(0)}px)`;
requestAnimationFrame(animate);
};

</script>
</body>

</html>

Why is my cursor not accepting the cursor: pointer property?

I’m trying to set cursor: pointer on some li’s in my nav bar but im running into some strange behaviour that I cant find the answer to anywhere online, nor does chat gpt know what to do. If i set cursor: pointer on any element, it will only work on a very thin margin of the border of an element before being reset to default.

I have tested the behaviour on a stand alone div with a nested anchor tag and it does the same. I have checked my style sheet and there are no conflicting styles or inheritence issues. I am using firefox dev edition, but I have tried it in codepen, firefox and chrome and i get the same behaviour. I literally can’t figure it out.

Using .map function to return data in a JSON file. Error saying its not a function

I’m getting data from an API and I parse it with JSON.parse. I then try to use .map to return the values in the keys. I’m not sure how to explain this and i’ve tried looking up ways to solve it. I’m trying to return it to a google sheets. I’m new to programming but I figure this isn’t something too hard to solve. Ill attatch a photo. Heres the video that I followed

link

Picture of code

I tried looking up solutions, and i’ve tried doing “data.products.map(items ……)” but I get an error saying .map is undefined

result

can someone help me to fix this error from nextjs and reactquery?

in this code, I created a multiple hooks with react query, and I import them in my component, but the error occurred when I am calling the useAddStudent and useDeleteStudent (in different component) at the same time (this the error:
Unhandled Runtime Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    )
import services from "./services";
import { useQuery, useMutation, useQueryClient, QueryClient } from '@tanstack/react-query';

export const useAllStudents = () => {
  return useQuery({ 
    queryKey: ['students'],
    queryFn: services.getAllStudents, //api call
    // staleTime: Infinity,  // it won't refetch your query and throw cache result
  });
}

export const useAddStudent = () => {
  const { invalidateQueries } = useQueryClient();
  return useMutation({
    mutationFn: (data: object) => services.addStudents(data), //api call
    onSuccess: () => {
      invalidateQueries({ queryKey: ['students'] });
    }
  })
}

export const useDeleteStudent = () => {
  const { invalidateQueries } = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => services.deleteStudent(id), //api call
    onSuccess: () => {
      invalidateQueries({ queryKey: ['students'] });
    }
  })
}
// this from delete component
const { mutate: mutation } = useDeleteStudent();
async function handleClick(id: any) {
  console.log('You have clicked this delete button');
  mutation(id);
}

// this from form component
 const { mutate: mutation } = useAddStudent();
  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    mutation(form)
  }

I have tried to read this information from the react query documentation. but it’s a bit confusing

The useQueryClient hook returns the current QueryClient instance.

tsx
import { useQueryClient } from '@tanstack/react-query'
const queryClient = useQueryClient(queryClient?: QueryClient)

Options

queryClient?: QueryClient,
Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.

How can make chart starts from centerline of chart plot at Highchart js?

I am using areaspline chart type at highchart. My series that i haved used in this chart is defined as follows:

var data = [{ datetime: '08:35', value: '2087696.02'},
{datetime: '08:40', value: '2087696.02'},
{ datetime: '08:45', value: '2087696.02'},
{datetime: '08:50', value: '2087696.02'},
{datetime: '08:55', value: '2087696.02},
{datetime: '09:00', value: '2087696.02},
{datetime: '09:05', value: '2088225.04'},
{datetime: '09:25', value: '2088505.21'}]

How can make the chart starts from centerline of chart plot?

How can I trigger automatically printing to pdf upon submission with NextJS and React-pdf?

I have a submission form where I would like to call a function to automatically generate a PDF when submitted. However, the submission form is done in a server component. What I also would like to do here is to pass the order_id to the generating PDF:

// Create Document Component
  export function BasicDocument({order, total, user, order_id} : BasicDocumentProps) {
    return (
        <Document>
          {/*render a single page*/}
          <Page size="A4" style={styles.page}>
          <InvoiceTitle title='Your Order'/> //pass the order_id here
          <View>
            <Text>Cart Items: {JSON.stringify(order, null, 2)}</Text>
          </View>
          <View>
          </Page>
        </Document>
    );
  }
  export default BasicDocument;

My form submission:

'use server'

import { createServerActionClient} from "@supabase/auth-helpers-nextjs"
import { cookies } from "next/headers"


export default async function addCustomerOrder(cart: any, total: number, formData: FormData): Promise<{ message: string }> {     
    const cookieStore = cookies()
    const supabase = createServerActionClient({ cookies: () => cookieStore })

    try{
            //rest of the codes

              
                //this is the order_id that I would like to pass on the generating of the PDF.
                const order_id = orderData?.[0]?.order_id;
                
                //rest of the codes...
            return {  message: `Succesfully added the data` }
    }catch(e){
        return {message: "Failed to submit the form."}
    }

}

To generate a PDF: In generating this PDF, this kind of serves as a button from the react-pdf

 <PDFDownloadLink document={<BasicDocument cart={cart} total={total} user={user}/>} fileName="my-order.pdf">
        {({ blob, url, loading, error }) =>
          loading ? 'Loading document...' : 'Download now!'
        }
      </PDFDownloadLink>