Why items appends to the redux rather than replace?

I’m newbie to Reactjs. The problem I’m encountered:

When Article page loads in the first time, all is fine and there are 10 articles shown. When I click on the browser back button, and then I go to the Article page for the second time, the article-list will be duplicated (so, it will be 20 articles). If I do so again, it will be 30 articles and so on ..

I want to know, why the result of API call appends for the Redux and not replace? In other word, how can I clean the Redux on page load every time? The expected result is seeing always 10 item (articles) on the page Article when I open it.


Here is a simplified of the element (for navigating to the list of articles) in the main page:

import Pages from "Constants/Pages";

const Component = () => {

    const history = useHistory();
    const navigateWithToken = (page) => {
        history.push(page);
      }
    };
    
    return (
        <div className="d-flex align-items-center flex-column py-1 ">
          <div
            className="main-footer-btn-article"
            onClick={() => navigateWithToken(Pages.Articles)}
          ></div>
          <span className="main-footer-btn-text">Articles</span>
        </div>
    )
};

export const ArticlesBtn = memo(Component);

Also, here is the Article page:

import { memo, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";

import PostItems from "SharedComponents/PostItems";
import { getAllPosts } from "Redux/Actions";
import Pages from "Constants/Pages";

const Page = () => {
  const posts = useSelector((state) => state?.articles?.posts?.items);
  const dispatch = useDispatch();
  const { push } = useHistory();
  useEffect(() => {
    dispatch(getAllPosts());
  }, []);

  const onClickPost = (item) => {
    push({
      pathname: Pages.SingleArticle,
      state: {
        postId: item.id,
        title: item.subject,
        is_saved: item.is_saved,
      },
    });
  };

  return (
    <div className="full-height overflow-auto">
      { 
        posts?.map((item, index) => {
          return (
            <PostItems
              {...item}
              key={item.id}
              index={index}
              onClickPost={() => onClickPost(item)}
            />
          );
        })
      }
    </div>
  );
};

export default memo(Page);

Also here is the API call:

const getAllPosts = (page = 1) => {
  return async (dispatch: ReduxDispatch) => {
    //"posts?for=for_website"
    dispatch(toggleLoading(true));
    try {
      const { data } = await axios({
        method: "GET",
        url: "posts?for=for_mobile",
        params: { page: page },
      });
      const items = data?.data?.data;
      const pagination = {
        current_page: data.data.current_page,
        last_page: data.data.last_page,
      };
      dispatch(
        dispatchItemToRedux({
          type: ReducerTypes.GET_ALL_POSTS,
          payload: {
            items,
            pagination,
          },
        })
      );
    } catch (err) {
      return Promise.reject(err);
    } finally {
      dispatch(toggleLoading(false));
    }
  };
};

How to build an API using C++

I would like to create a simple C++ program that extracts data from a website and then manipulates that data. For example, typing in a stock name in the C++ program and receiving the current price from Yahoo Finance. Would a backend framework be needed to perform this task and if so, would it be better to use a JavaScript framework since there are far more resources online about JS frameworks? Thank you in advance for answering this question and please break it down so a beginner like myself can understand and apply it to similar scenarios.

Resolving multiple promises inside an observable not working

I’m using Firebase Storage and I’m trying to load all assets via a function call. The only way to get an assets url is to call getDownloadURL which returns a promise. I need to call this for every asset but I can’t make it wait for all promises to be done before continuing for some reason.

I thought returning a promise from mergeMap would make it wait for all of them but that doesn’t seem to be the case.

I’ve look at a number of questions regarding promises and RXJS but I can’t seem to figure out what’s wrong with the code.

getAssets() {

    return this.authService.user$.pipe(
      first(),
      switchMap(user => defer(() => from(this.afs.storage.ref(`${user.uid}/assets`).listAll()))),
      switchMap(assets => from(assets.items).pipe(
        mergeMap(async (asset) => {
        
          return new Promise((res, rej) => {
          
            asset.getDownloadURL().then(url => {
              
              const _asset = {
                name: asset.name,
                url,
              };
  
              this.assets.push(_asset);

              res(_asset);
            })
            .catch((e) => rej(e));
          });
        }),
      )),
      map(() => this.assets),
    );
  }

  ...

  this.getAssets().subscribe(assets => console.log(assets)); // this runs before all asset's url has been resolved

DiscordJS move all members in a specific vc

I’m trying to find a way to move all members which are in a specific vc to the vc which the sender of the command is in. The command should be -warp. This is what i have so far:

        if (!message.member?.permissions.has('MOVE_MEMBERS')) return;
        const member = message.mentions.members?.first();
        if (!member) return message.reply("Error: Didn't specify member.");
        if (!member.voice.channel) return message.reply("Error: Mentioned member is not in a Voice Channel.");

        if (!message.member.voice.channel) return message.reply("Error: Executor of command is not in a Voice Channel.");
        member.voice.setChannel(message.member.voice.channel)
        message.reply('Success: Moved member.')

It works but i can only move one user at the time and from every vc. I want everyone to be able to move others but only from a specific vc.
Thanks for your help!

Updating div results text on that specific link click

What I’m trying to do is display on-screen messages back “success” or “error” inside the table row the user clicks a link on, if row 17 is clicked the message appears in row 17’s <div class="status"></div> status message div.

Relevant code:

                    <td>
                        <strong>URL:</strong> <a href="https://www.example.com<?= $node["productLink"]; ?>" id="productLink" class="text-decoration-none" target="_blank">https://www.example.com<?= $node["productLink"]; ?></a>
                        <br />
                        <strong>Product Name:</strong><small> <?= $node["productDescription"]; ?></small>
                        <br />
                        <strong>Price:</strong> <span class="text-success"><?= $node["productPrice"]; ?></span>
                        <br />
                        <strong>Status:</strong> <a href="#" data-bs-toggle="tooltip" data-placement="bottom" class="importProduct" value="https://www.xxx.co.uk<?= $node["productLink"]; ?>|<?= $node["productImage"]; ?>|<?= $node["productDescription"]; ?>|<?= $node["productPrice"]; ?>|<?= $_POST['xxx_search_catid']; ?>" title="Add to your shop"><i class="fas fa-file-import"></i> <div class="status"></div></a>
                    </td>                           
            
                <?php } ?>                          
            </tr>   
            
        <?php } ?>  
  </tbody>    
</table>
</div>   

<script type="text/javascript">  
$(document).ready(function(){     
   $(".importProduct").on('click', function(e) {
      e.preventDefault();  
      var productDetails = $(this).attr('value');
      $.ajax({  
         type:"POST",  
         url: "https://www.example.com/ajax-import.php",  
         data: {
                "xxx_data":productDetails                               
                },
         success: function(results) {  
            $('.status').html(results);
            //alert("Successfully added product to the shop!");
         },
         error: function(data) {
            alert("Uh oh! AJAX error!");
         }  
      });  
   }); 
});        
</script> 

The way the code is now, all rows display “success” in the <div class="status"></div> part, Ideally it should only be the row the button is clicked on, on a success in Ajax this is where the messages are returned and printed $('#status').html(results);.

I’m guessing at this point $('.status').html(results); I need to identify the row somehow to to only update that .status?

I am unsure what to try, any tips would be appreciated.

MongoDB Count By Current Month

I’m new to MongoDB. I need to get the count of the posts which are posted in this current month. PlateModel is my model I’ve kept timestamps true also. It looks like the below:

  { timestamps: true }

My present code in the Controller looks like below:

 const today = new Date();
    const host_count = await PlateModel.find({
      $and: [
        {
          postedBy: req.user._id,
        },
        {
          createdAt: today.getMonth(),
        },
      ],
    }).count();

But, I get the count value 0. Can anyone help me to figure out the problem?

How do I deploy my app built with Node.js and Nextjs. I use Express.js but I dont mind changing it if there is a workarounf

I built an app with Node.js & express as backend and Next.js as frontend and I also use concurrently to connect both. Now I’m done with building and I need to deploy the app, I have found not source on how to deploy this. Pls how can I deploy this on heroku or any other source. I’m finding it tough to do this. Thanks.

Adding a game score to a tweet template

I’ve created a quiz type of website and I was wondering how I can change my code to add the score to the tweet

<button class="tweet-score" onclick="window.location.href="window.location.href="//twitter.com/intent/tweet?text=Check%20out%20my%20score%20on%20this!%3A&url=http%3A%2F%2Fexample-quiz.com/%2F">Share your score</button>

To display the score on the results html page, I just use #score with the CSS being as simple as:

#score{
    font-size: 100px;
    margin: 50px 0px;
}

Here is the JavaScript:

function showScore(){
    var queryString = window.location.search
    var score = new URLSearchParams(queryString).get("score")

    $('#score').html(score + '/10')
}

NestJS/TypeORM: Cannot set property metadata of # which has only a getter

I try to run my nestjstutorial app, the below error is showing. My backend is connected to a PostgreSQL db.

TypeError: Cannot set property metadata of # which has only a getter
at EntityManager.getCustomRepository (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialsrcentity-managerEntityManager.ts:1404:59)
at DataSource.getCustomRepository (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialsrcdata-sourceDataSource.ts:465:29)
at InstanceWrapper.useFactory [as metatype] (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialnode_modules@nestjstypeormdisttypeorm.providers.js:13:35)
at Injector.instantiateClass (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialnode_modules@nestjscoreinjectorinjector.js:333:55)
at callback (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialnode_modules@nestjscoreinjectorinjector.js:48:41)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Injector.resolveConstructorParams (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialnode_modules@nestjscoreinjectorinjector.js:122:24)
at Injector.loadInstance (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialnode_modules@nestjscoreinjectorinjector.js:52:9)
at Injector.loadProvider (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialnode_modules@nestjscoreinjectorinjector.js:74:9)
at Injector.lookupComponentInImports (D:GaneshMyDrivenestjsnestjs_tutorialnestjsturorialnode_modules@nestjscoreinjectorinjector.js:265:17)

My code looks like this:

app.module

    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { UserController } from './user/user.controller';
    import { UserModule } from './user/user.module';
    import { UserService } from './user/user.services';
    import { QuizModule } from './modules/quiz/quiz.module';
    //import { QuizController } from './modules/quiz/quiz.controller';
    //import { QuizService } from './modules/quiz/quiz.services';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { typeOrmConfig } from './config/typeorm.config';
    //import { QuizRepository } from './modules/quiz/quiz.repository';
    
    @Module({
      imports: [UserModule, QuizModule, TypeOrmModule.forRoot(typeOrmConfig)],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}

quiz.controller

    import {
      Body,
      Controller,
      Get,
      HttpCode,
      Post,
      UsePipes,
      ValidationPipe,
    } from '@nestjs/common';
    import { QuizService } from './quiz.services';
    import { CreateQuizDto } from '../dto/CreateQuiz.dto';
    
    @Controller('quiz')
    export class QuizController {
      constructor(private readonly quizService: QuizService) {}
    
      @Get('/')
      getAllQuiz() {
        return this.quizService.getAllQuiz();
      }
    
      @Post('/create')
      @HttpCode(200)
      @UsePipes(ValidationPipe)
      async createQuiz(@Body() quizData: CreateQuizDto) {
        return await this.quizService.createNewQuiz(quizData);
      }
    }

quiz.services

    import { Injectable } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { QuizRepository } from './quiz.repository';
    import { CreateQuizDto } from '../dto/CreateQuiz.dto';
    
    @Injectable()
    export class QuizService {
      constructor(
        @InjectRepository(QuizRepository) private quizRepository: QuizRepository,
      ) {}
    
      getAllQuiz() {
        return [1, 2, 'from service', 3];
      }
      async createNewQuiz(quiz: CreateQuizDto) {
        return await this.quizRepository.save(quiz);
      }
    }

quiz.module

    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    import { QuizController } from './quiz.controller';
    import { QuizService } from './quiz.services';
    import { QuizRepository } from './quiz.repository';
    
    @Module({
      controllers: [QuizController],
      imports: [TypeOrmModule.forFeature([QuizRepository])],
      providers: [QuizService],
    })
    export class QuizModule {}

quiz.repository

    import { EntityRepository, Repository } from 'typeorm';
    import { Quiz } from './quiz.entity';
    
    @EntityRepository(Quiz)
    export class QuizRepository extends Repository<Quiz> {
      //<Quiz> means Quiz module
    }

Somebody know how can I fix this?

How to sum each value inside array of object to new variable

I have a data like this :

const fund = 
[
 {
  id: 1234,
  totalAmount: 0,
  data: 
   [
    {
     id: 1234,
     amount: 4000
    },
    {
     id: 1234,
     amount: 3000
    }
   ]
 },
 {
  id: 12345,
  totalAmount: 0
 },
 {
  id: 123456,
  totalAmount: 0
  data: 
   [
    {
     id: 123456,
     amount: 3000
    },
    {
     id: 123456,
     amount: 5000
    }
   ]
 }
]

I want to sum the amount inside of data each id to a key called totalAmount. But not all the parent id have data key.

here’s my desired output :

const fund = 
[
 {
  id: 1234
  data: 
   [
    {
     id: 1234,
     amount: 4000
    },
    {
     id: 1234,
     amount: 3000
    }
   ],
  totalAmount: 7000
 },
 {
  id: 12345,
  totalAmount: 0        
 },
 {
  id: 123456,
  data: 
   [
    {
     id: 123456,
     amount: 3000
    },
    {
     id: 123456,
     amount: 5000
    }
   ],
  totalAmount: 8000
 }
]

I was trying with this code :

fund.forEach((elA, i) => {
        if (elA.data) {
          const total = funders[i].data.reduce((acc, curr) => {
            acc += parseInt(curr.loanAmount.replace(/./g, ''))
            return acc
          })
        }
      })

But it’s not summing like i want.

Where’s my mistake ?

Please ask me if you need more information if it’s still not enough to solve that case.

JS class variable not setting [duplicate]

I have created an AJAX promise and when it is complete I am trying to set a class variable but it is not setting for some reason. I thought this was an ASYNC issue but the promise should have resolved that issue. It’s possible it is a scope issue but I don’t know how to resolve it.

$(document).ready(function(){

class Tables {

    constructor() {
       Tables.Action   = this.GetAction()
       Tables.Headers  = ''

      this.InitHeaders()

      console.log(Tables.Headers)
    //this.InitDatables()


    }
    GetAction() {
      var Segments  = window.location.pathname.split("/")
      var URL       = '/'+Segments[1]

        return URL
    }

    InitHeaders(){

        this.GetHeaders().then(function(data) {
            // Run this when your request was successful
            Tables.Headers = data
          }).catch(function(err) {
            // Run this when promise was rejected via reject()
            console.log(err)
          })
    }
    GetHeaders()
    {
       return new Promise(function(resolve, reject) {
            $.ajax({

              url     : Tables.Action +'/GetHeaders',
              success: function(data) {
                    resolve(data) // Resolve promise and go to then()
              },
              error: function(err) {
                reject(err) // Reject the promise and go to catch()
              }
            })
          });

    }

  }

let Table = new Tables();


});

How to add JWT auth and private or public key in react native keychain?

I am trying to create one login/signup page which is storing the value in keychain and I am trying to store the JWT token while login on device and public key get store on server side the private key store in client side will ask for biometric and take to home page.

Login.tsx

const login: SubmitHandler<ILoginValues> = async ({email, password}) => {
    try {
      const res = await fetch(`${config.apiUrl}/api/login`, {
        method: 'POST',
        body: JSON.stringify({
          email,
          password,
        }),
      });
      if (res.ok) {
        await setGenericPassword(email, password, CREDENTIALS_STORAGE_OPTIONS);
        setUser({isLoggedIn: true, hasSessionExpired: false});
        toast.setToast({message: 'Login has succeeded', visible: true});
      }
    } catch (error) {
      toast.setToast({message: 'Login failed', visible: true});
    }
  };

Biometric handle part

  const handleBiometricsLogin = useCallback(async () => {
    if (!user?.hasSessionExpired) {
      toast.setToast({message: 'No expired session'});
      return;
    }
    try {
      const credentials = await getGenericPassword(CREDENTIALS_STORAGE_OPTIONS);
      console.log({credentials});
      if (!credentials) {
        return;
      }
      const res = await fetch(`${config.apiUrl}/api/login`, {
        method: 'POST',
        body: JSON.stringify({
          email: credentials.username,
          password: credentials.password,
        }),
      });
      if (res.ok) {
        setUser({isLoggedIn: true, hasSessionExpired: false});
        toast.setToast({
          message: 'Login with biometrics has succeeded',
          visible: true,
        });
      }
    } catch (error) {
      toast.setToast({message: 'Login with biometrics failed'});
    }
  }, [setUser, toast, user?.hasSessionExpired]);

Requirements

When a user enrolls in biometrics, a key pair is generated. The private key is stored securely on the device and the public key is sent to a server for registration. When the user wishes to authenticate, the user is prompted for biometrics, which unlocks the securely stored private key. Then a cryptographic signature is generated and sent to the server for verification. The server then verifies the signature. If the verification was successful, the server returns an appropriate response and authorizes the user.

Login onSubmit not redirecting to another html file

I made a login with javascript where if you enter the correct username and password you can enter the home page. You can find the username and password in the script. I finish the javascript code and I tested the login. When I entered, it did not redirect to the home page html file but instead just reloaded. The main problem is that, when I submit/login the username and password, it is not going home page html file. Here is the code:

 function Login() {
        var username = document.getElementById("user").value;
        var password = document.getElementById("pass").value;
        if (username == "will" && password == "will") {
          window.location.href = "home.html";
        } else {
          alert("Sadly, your not in the club");
        }
      }
 @import url("https://fonts.googleapis.com/css2?family=Amatic+SC&display=swap");

      * {
        font-family: "Amatic SC", cursive;
        text-align: center;
      }

      form {
        text-align: center;
        justify-content: center;
        height: 400px;
      }

      h1 {
        padding: 30px;
      }

      input,
      button {
        padding: 10px;
        width: 110px;
        font-size: 30px;
      }
    <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>.WWW Login</title>
  </head>
  <body>
    <form>
      <h1>.WWW Login</h1>
      <input placeholder="Username" type="text" id="user" required />

      <br />
      <br />

      <input placeholder="Password" type="password" id="pass" required />

      <br />
      <br />
      <button onclick="Login();">Login</button>
    </form>
  </body>
</html>