How do I retrieve data from another variable using array.map?

In the return code below, I am mapping over user.posts to render a list of posts, if there is a user. In the Post component, the prop is passed in from user.post variable, however for the username prop, the data is inside the uservariable. What should I do in order to get the data to be passed into username prop?

const UserPosts = () => {
    const [user, setUser] = useState()


    useEffect(() => {
        const id = localStorage.getItem("userId");
        const sendRequest = async () => {
            const res = await axios.get(`/post/user/${id}`)
                .catch(error => console.log(error));
            const data = await res.data;
            console.log(data)
            return data;

        }

        sendRequest()
            .then((data) => setUser(data.user))
    }, [])

    console.log(user)

    return (
        <div>
            {user &&
                user.posts.map((post, index) => (
                    <Post
                        key={index}
                        username={post.username}
                        caption={post.caption}
                        selectedFile={post.selectedFile}
                        createAt={post.createAt}
                    />
                ))}
        </div>
    )
}

I want the units=metric from the api to change to imperial when clicking a button. How can I do that

let weather = {
    "apiKey": 'd25049c086d39071209ae4f3c7002172',
    fetchWeather: function(city){
        fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city + 
        '&units=metric&appid='+ this.apiKey)
        

Here, where it says units=metric, I want it to change to imperial or metric when a button is clicked.

        .then((response) => response.json())
        .then((data) => this.displayWeather(data));
    },

Mongoose – session abortTransaction is not rolling back

I don’t know what I’m missing but in the block catch session.abortTransaction() not rolling bak anything. I purposely used throw new Error(“Error message”) after the creation of a user to land in the catch block to trigger the session.abortTransaction() but when I look in the database I see that the user is still created despite the abortion.

Here is my source code

export const signUp = async (req, res) => {
    const { email, password, fullname } = req.body;
    // Init session
    const session = await mongoose.startSession(); 
    // Begin transaction
    session.startTransaction(); 
    try {
        // Check if user exist in database using his email
        const dbUser = await UserModel.findOne({ email }, null, session);

        // Return a conflit code if user already exist
        if (dbUser) return res.status(409).json({ message: "User already exists" });
        
        // Create tenant
        const tenantResult = await TenantModel.create([{ createdAt: new Date() }], null, session);

        // Get admin role
        const roleResult = await RoleModel.findById('626db17b8645717d657fc4c8', null, session);

        //Hash password using jwt
        const hashedPassword = await bcrypt.hash(password, 12);

        
        // Store user in db
        const userResult = await UserModel.create([
            { 
                email: email, 
                password: hashedPassword, 
                fullname: fullname, 
                tenant: tenantResult[0], 
                role: roleResult 
            }
        ], null, session);
        throw new Error("Error message");

        if (userResult){
            // Create subscription && currency
            
            // Create currency for user
            await CurrencyModel.create([
                {
                    name: 'Dollar', 
                    createdAt: new Date(),
                    symbol: '$', 
                    isoCode: 'USD', 
                    default: true,
                    userRole: 'setting-list',
                    createdBy: userResult[0],
                }
            ], null, session);
        }

        // Generate token using jwt, secret, and user data
        const token = jwt.sign( { email: userResult[0].email, id: userResult[0]._id }, secret, { expiresIn: "24h" } );

        // Send welcome email to registered user
        await sendWelcomeEmail(userResult[0].email, userResult[0].fullname, `Welcome ${userResult[0].fullname} - light-speed.dev`, 'welcome-email.html');
        
        //Commit transaction
        await session.commitTransaction();

        // Return 201 Created http code with user and token
        return res.status(201).json({ userResult, token });
    } catch (error) {
        // Abort transaction if one of these request throw error
        await session.abortTransaction();
        console.log(error);
        return res.status(400).json({ message: 'Something went wrong!' });

    } finally {
        // close session
        session.endSession();

    }
};

Thank you for your help!

Can’t move parallex or get it to be as wide as screen

Hi I’ve been trying to imploment a parallex image into a page today but I cant get the image to be as wide as the page (gets close but leaves a small gap) and also it won’t move at all only dissapears when I change position to absolute.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="parallax.min.js"></script>

<div class="container">

        <div class="parallax" data-parallax="scroll" data-z-index="1" data-image-src="pexels-emiliano-arano-1350197.jpg">

            </div>
            
        </div>

.container {
    max-width: 100vw;
    margin: 0 auto;
}

.parallax {
    min-height: 500px;
    background: transparent;
    
}

await multiple texts from user before moving to next step in scene telegram bot (telegraf)

Greetings fellow developers,

I’ve built a telegram bot using telegraf. I’m currently looking for a way to make my bot wait for a certain amount of texts from user before moving to the next step.
example:
bot asks how many texts the user will send
the user: 30
the bot waits for 30 texts to be sent by user then proceeds to the next step

    const askamountStep=new Composer()
    askamountStep.on("text",async(ctx)=>{
    try{
    ctx.replyWithHTML("How many texts are you planning on sending?")
    return ctx.wizard.next()
    }
   catch(e)
   {
   console.log(e)
   }
   })
   const savetextsStep=new Composer()
   savetextsStep.on("text",async(ctx)=>{
   try{
   ctx.wizard.state.data.amount=ctx.message.text
   const wizardData= ctx.wizard.state.data
   for (i=0;i<wizardData.amount;i++)
   {
    savetextsStep.on("text",async(ctx)=>{
   const wizardData+= ctx.wizard.state.data
   })}
    console.log(wizardData.texts)
    ctx.replyWithHTML("30 texts 
    recieved",Markup.inlineKeyboard([     
    [Markup.button.callback('Okay','ok')]
                                
                            ]))
     return ctx.wizard.next()
    }
  catch(e)
                            {
                                console.log(e)
                            }
   })

Your help would be highly appreciated.

Typescript – Convert “object with promises as properties”-Type to “object with resolved promise values as properties”-Type

Is this possible in Typescript?

I want to turn e.g. something like this:

interface IPromiseObject {
promiseA: Promise<number>;
promiseB: Promise<string>;

}

Into this:

interface IResolvedPromiseObject {
    promiseA: number;
    promiseB: string;
}

I want to use it to resolve an object with promises as values, but still stay type safe. In this example, I need to convert IPromiseObject to an object with the same keys but the values resolved so that I can use it as return type.

export async function resolveAllObject<IPromiseObject>( promiseObject: IPromiseObject ): Promise<???> {
    const resolvedPromiseObject = {};
    for ( const key in promiseObject ) {
        const value = await promiseObject[ key ];        
        Object.assign( resolvedPromiseObject, { [ key ]: value } );
    }
    return resolvedPromiseObject;
}

Sorting Numbers in ascending Order in Typescript

I´ve to code a program, which orders three Numbers of an input on a website in ascending order. My HTML looks like this:

<section>
    <h3 class="section-heading">Zahlen sortieren</h3>
    <form id="sort">
        <input  class="form-control" id="zahl1">
        <input  class="form-control" id="zahl2">
        <input  class="form-control" id="zahl3">
        <button type="submit" class="btn btn-info btn-block">sortieren</button>
    </form>
    <p id="output"></p>
</section>

Can somebody help me out please?

How to find time period of compound interest with help of a formula

I am making a compound interest calculator, and want to input minimum 3 input fields from “amount”, “compound interest”, “time” and “rate”. I can calculate the remaining field by the data provided but the problem comes when I have to find the value of “time”.
Now, take a simple example of p = $1000, r =10% pa and A = 1210.
I know that the answer for time is 2 years, but I have to use formula.
After I searched, I got formula: t = log10(A/P) / (n*log10(1+R/n))
here n is how much times I have to compound annually, i.e. 1 times so it is 1
so formula will become t= log10(1210/1000)/1*log10(1+10/1)
which ultimately is log10(1.21)/log10(11)
Now putting it in javascript, const t = Math.log10(1.21)/Math.log10(11) gives answer as 0.079494864421745, while the actual time is 2. Can you please tell where I am doing wrong. Also if you can give me an overview of putting outstanding value in my calculator, please do help me. Thanks

ES5 JavaScript: Find specific property in nested objects and return its value

I need to return the value of a specific property of nested objects with ES5 syntax. Every object can have its own structure, so the needed property can be on different levels/places. E.g. -> I have three different objects and the value of property “source” is needed:

  • first_data has that property in list.details.source
  • second_data has that property in list.details.products[0]._new.source
  • third_data does not have this property, therefore it should return false
var first_data = {
    area: "South",
    code: "S265",
    info: {
        category: "enhanced",
        label: "AB | 27AS53",
        variable: "VR"
    },
    list: {
        area: "Mid",
        details: [
            {
                source: "Spain",
                totals: 12,
                products: [
                    {
                        name: "ABC",
                        brand: "Nobrand",
                        id: "111",
                        category: "Men",
                    }
                ]
            }
        ]
    },
    time: 1654775446138
};

var second_data = {
    area: "South",
    code: "S265",
    info: {
        category: "enhanced",
        label: "AB | 27AS53",
        variable: "VR"
    },
    list: {
        area: "Mid",
        details: [
            {
                products: [
                    {
                        name: "ABC",
                        brand: "Nobrand",
                        id: "111",
                        category: "Men",
                        _new: {
                            source: "Spain",
                            totals: 12
                        }
                    }
                ]
            }
        ]
    },
    time: 1654775446138
};

var third_data = {
    area: "South",
    code: "S265",
    info: {
        category: "enhanced",
        label: "AB | 27AS53",
        variable: "VR"
    },
    list: {
        area: "Mid",
        details: [
            {
                products: [
                    {
                        name: "ABC",
                        brand: "Nobrand",
                        id: "111",
                        category: "Men"
                    }
                ]
            }
        ]
    },
    time: 1654775446138
};

JavaScript Filtering

I am trying to build a filter that filters an array based on qualification and years of experience among other criteria after clicking the filtering button, I am new to JavaScript and as such I have encountered many challenges. Ideas on how best I can implement this will be highly appreciated.
The code is here:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>APPLICANT FILTERING</title>
</head>

<body>
  <h1>FILTER APPLICANTS</h1>
  <button onclick="newArray()">CLICK TO FILTER</button>
  <p id="demo"></p>

  <script>
    var obj = {
        'applicants': [{
            "name": "Tom",
            "qualification": "degree",
            "experience": "5 years}, {
              "name": "David",
              "qualification": "certificate",
              "experience": "2 years"
            },
          ]
        };
        var newArray = obj.applicants.filter(function(el) {
          return el.qualification = 'degree' &&
            el.experience >= 5;
        });
        console.log(newArray);
        document.getElementById("demo").innerHTML = text;
  </script>
</body>

</html>

convert string into 2D-array format in JavaScript

I’m getting string from database and i need to convert it in the format below:

var locations = [
  ["LOCATION_1", 11.8166, 122.0942],
  ["LOCATION_2", 11.9804, 121.9189],
  ["LOCATION_3", 10.7202, 122.5621],
  ["LOCATION_4", 11.3889, 122.6277],
  ["LOCATION_5", 10.5929, 122.6325]
];

my code below

                   var array = ''
                   var arrayprev= ''
                   for (var i = 0; i < obj.length; i++) {
                        array = '['+obj[i].Location + '"' + ',' + obj[i].x + ',' + obj[i].y + '],|'
                        if (arrayprev == "") {
                            arrayprev = array;
                        }
                        else {
                            arrayprev = arrayprev + array;
                        }
                    }
                   locations = arrayprev.split("|")

i’m getting only chracters when passing in code below

for (var i = 0; i < locations.length; i++) {
        marker = new L.marker([locations[i][1], locations[i][2]], { icon: iconColor(color) })
            // PoPup result will be displayed here
          .bindPopup(locations[i][0])
            //here tool tip will be used to display the label text
          .bindTooltip(locations[i][0],
            {
                permanent: true, 
                direction: 'right'
             }
            )
          .addTo(map);

hardcoded location array is working fine but when I use my loop I’m not getting the correct data Please help

Flat json data for antd table

Have a JSON data

[
    {
        "packageName": "Test 2",
        "providerOperatorCommissionInfos": [
            {
                "commissionInfoIndex": 0,
                "apiSlabs": [
                    {
                        "min": 0,
                        "commissionType": "COMMISSION",
                        "amountType": "FIXED",
                    },
                    {
                        "min": 101,
                        "commissionType": "SURCHARGE",
                        "amountType": "PERCENT",
                    }
                ],
                "operatorName": "Jio",
                "operatorIdentifier": "74a00b21-012b-4fb4-a6d5-3a87653b15ac",
                "operatorCategory": "PREPAID"
            },
            {
                "commissionInfoIndex": 1,
                "apiSlabs": [
                    {
                        "min": 0,
                        "commissionType": "SURCHARGE",
                        "amountType": "PERCENT",
                    },
                    {
                        "min": 1001,
                        "commissionType": "COMMISSION",
                        "amountType": "FIXED",
                    }
                ],
                "operatorName": "Airtel",
                "operatorIdentifier": "e14ddeba-40cd-4956-9645-aa4f92f749fc",
                "operatorCategory": "PREPAID"
            }
        ]
    }
]

In order to use it with antd table, it needed beNeed to flat the data at providerOperatorCommissionInfos so that it will be an object and also apiSlabs will be an object.

For eg:
Test 2 will be be flatten as 4 objects where providerOperatorCommissionInfos and apiSlabs will be objects as well.

How can I flatten the json?

How to read “Set-cookie” from a header response in React

I can not read my cookie from the header response marked with the Set-Cookie key in my browser.

I can read and get everything in the header response except for the Set-Cookie.

My cookie is in the response header in my browser but I can not get or read it in my React project.

I noticed that it is not possible to get Set-Cookie in JavaScript.

I even have an extra tab called Cookies in my browser in the Inspect section and on the Network tab, in addition to the Headers, Payload tabs, etc., that contain my cookies.

I want to know how to save my cookie after logging in?

I use axios and Redux.

Thanks to those who help me!

css-vue-how to keep a navbar item state before router change

I have a Vue.js project. It has two sides, the left is the navbar and the right is router-view component.
The navbar has four blue buttons. All of them can lead to different routes on the right side(url changes too).
I want to achieve the effect as follows: when one of them is clicked, the page enters the corresponding route and the button turns red then stay red. When any other button is clicked, the button just clicked turns red and the previous one turns back to blue. I am thinking about the way child component passes value to the parent component. On second thougnt, I think it too complecated. Is there a better way?