How to connect different MongoDB collections to React

Please help me out with this as I can’t find the answer anywhere.

My MongoDB Database name is myWebsiteDB:

  • myWebsiteDB has 2 collections: dinners and emails.
  • I have connected dinners collection to use in my website as a CRUD app – works fine.
  • Now I want to save data from Email Subscription section’s input field to the emails collection on my website.
  • These 2 collections are for saving 2 different data intentions, so I don’t want to join them.

I tried setting up the emails collection Schema and connecting it to my React App exactly like the way I connected the dinners collection before, here are the challenges that I’m facing:

  1. When I click the Submit Email button, it doesn’t work and the errors returned from the server’s terminal seem like it’s the validation for the dinners collection, not the emails collection that I
    m trying to write in. See screenshot

  2. Am I using validator and writing the new Emails schema right? Do I need to specify the {collection: collection name} like below?

Here are my code:

Emails Model (Emails.js):

const mongoose = require('mongoose')
const validator = require('validator')

const EmailSchema = new mongoose.Schema({
    email: {
        type: String,
        trim: true,
        lowercase: true,
        unique: true,
        validate: {
            validator: validator.isEmail,
            message: 'Please input a valid email address',
            isAsync: false
        }
    }
}, {collection: "emails"})

const Emails = mongoose.model('Emails', EmailSchema)
module.exports = Emails

Dinner Model (Dinner.js):

const mongoose = require('mongoose')

const DinnerSchema = new mongoose.Schema({
    foodName: {
        type: String,
        required: true,
    },
    isVegetarian: {
        type: Boolean,
        required: true,
    },
    priceRange: {
        type: String,
        required: true,
    }
}, {collection: "dinners"})

const Dinner = mongoose.model("Dinner", DinnerSchema)
module.exports = Dinner

Server side index.js:

const express = require("express") // Set up an express server
const mongoose = require("mongoose") // Import Mongoose library
const cors = require('cors') // Import CORS to communicate with frontend
const app = express() // Initializing our express server

const DinnerModel = require('./models/Dinner')
const EmailModel = require('./models/Emails')

app.use(express.json()) // Setting up Middleware
app.use(cors())

// Connect to MongoDB
mongoose.connect(
    'mongodb+srv://myusername:[email protected]/myWebsiteDB?retryWrites=true&w=majority', 
    {
        useNewUrlParser: true,
    }
)

// Create:
app.post("/insert", async (req, res) => {
    const foodName = req.body.foodName
    const isVegetarian = req.body.isVegetarian
    const priceRange = req.body.priceRange
    const email = req.body.email

    // Dinner Ideas App:
    const dinner = new DinnerModel(
        { 
            foodName: foodName, 
            isVegetarian: isVegetarian,
            priceRange: priceRange,
        }
    )

    // Email:
    const emailData = new EmailModel(
        {
            email: email
        }
    )

    try {
        await dinner.save()
        await emailData.save()
        res.send("data inserted")
        
    } catch(err) {
        console.log(err)
    }
})

// Read:
app.get("/read", async (req, res) => {
    DinnerModel.find({}, (err, result) => {
        if (err) {
            res.send(err)
        }
        res.send(result)
    })
})

// Update:
app.put("/update", async (req, res) => {
    const newFoodName = req.body.newFoodName
    const id = req.body.id

    try {
        await DinnerModel.findById(id, (err, updatedFood) => {
            updatedFood.foodName = newFoodName
            updatedFood.save()
            res.send("update")
        }).clone()
    } catch(err) {
        console.log("The error is: " + err)
    }
})


app.delete("/delete/:id", async (req, res) => {
    const id = req.params.id

    await DinnerModel.findByIdAndRemove(id).exec()
    res.send("deleted")
})

// Creating a port:
app.listen(3001, () => {
    console.log("Server is up on: http://localhost:3001")
})

React code with CRUD using the dinners collection:

import React, { useState, useEffect } from "react"
import './DinnerIdeas.css'
import Axios from "axios"
import FoodListComponent from "../FoodListComponent";
import FormComponent from "../FormComponent";


function DinnerIdeas() {

    const [foodName, setFoodName] = useState('')
    const [isVegetarian, setVegetarian] = useState(false)
    const [priceRange, setPriceRange] = useState('$')
    const [newFoodName, setNewFoodName] = useState('')
    const [foodList, setFoodList] = useState([])
  
    // Read:
    useEffect(() => {
      let unmounted = false
      Axios.get("http://localhost:3001/read")
      .then((response) => {
        if (!unmounted) {
          setFoodList(response.data)
        }
      })
      .catch(error => {
        console.log(`Hey, the error is ${error}`)
        return
      })
      return () => {
        unmounted = true
      }
    }, [foodList])
  
    // Create:
    const addToList = () => {
      Axios.post(
        "http://localhost:3001/insert", 
        {
          foodName: foodName,
          isVegetarian: isVegetarian,
          priceRange: priceRange,
        }
      )
    }
  
    // Update:
    const updateFood = (id) => {
      if (newFoodName) {
        Axios.put("http://localhost:3001/update", {
          id: id,
          newFoodName: newFoodName,
        })
        .catch(error => console.log(`Hey, the error is ${error}`))
      }
    }
  
    // Delete:
    const deleteFood = (id) => {
      Axios.delete(`http://localhost:3001/delete/${id}`)
    }
    
    return (
      <section className="dinner-ideas">
        <FormComponent
          setFoodName={setFoodName}
          setVegetarian={setVegetarian}
          setPriceRange={setPriceRange}
          addToList={addToList}
        />
        <FoodListComponent 
          foodList={foodList} 
          setNewFoodName={setNewFoodName}
          updateFood={updateFood} 
          deleteFood={deleteFood}
          newFoodName={newFoodName}
        />
      </section>
    );
  }
  
  export default DinnerIdeas;

React Footer Component that let users put in their emails to subscribe, this will write to the emails collection:

import React, { useState } from "react"
import Axios from "axios"



export default function FooterComponent() {

    const [email, setEmail] = useState('')

    const subscribeEmail = () => {
        Axios.post(
            "http://localhost:3001/insert",
            {
                email: email
            }
        )
    }


    return (
        <footer>
            <div>Created by higherstates &copy; 2021</div>
            <div>
                <h3>Interested in further deals?</h3>
                <input
                    type='email'
                    placeholder="Give us your email"
                    onChange={(event) => {setEmail(event.target.value)}}
                />
                <button 
                    type="submit"
                    onClick={subscribeEmail}
                >
                    Submit Email
                </button>
            </div>
        </footer>
    )
}

Please guide me on how to fix this, thank you! 🙂

Using GSAP and ScrollTrigger to create a number counter (where numbers exist)

I have a section which showcases statistics.

  • Some of these statistics are numbers (i.e. 145);
  • Some are numbers, characters and symbols (i.e. 65K+ or $20.00)
  • Some are just purely text (i.e. “text”)

When this section is in view, I want stats which contain a number to count up (and naturally stats that don’t contain numbers to not count up).

The effect I’m trying to achieve is:

  • All .statsBannerCard‘s are set to visibility: hidden
  • User scrolls to section
  • JS checks if first .statsBannerCard contains number; if yes, counts up (this single card is visibility: visible now).
  • Then once the counter for the first card is complete, make the second card visible and check if it contains a number, and so on.

The proceeding card is essentially shown once the previous card counter is complete. If a card just contains text (so we can’t count up), it will just show the card and move on.

Current issue:

In my demo below, I’m using the data-number attribute to determine what number the card needs to count up to. When scrolling down, the first counter works (because it is a pure integer), however, it stops working when characters, symbols or letters are involved.

Demo:

$(function() {

  gsap.registerPlugin(ScrollTrigger);


  $(".statsBannerCard__statistic").each(function(index, element) {
    var count = $(this),
      zero = {
        val: 0
      },
      num = count.data("number"),
      split = (num + "").split("."), // to cover for instances of decimals
      decimals = split.length > 1 ? split[1].length : 0;

    gsap.to(zero, {
      val: num,
      duration: 2,
      scrollTrigger: element,
      onUpdate: function() {
        count.text(zero.val.toFixed(decimals));
      }
    });
  });

});
.spacer{
  height: 100vh;
  background: lightblue;
}

.statsBanner{
  background: #F283D6;
  padding: 100px 0;
}

.statsBanner__intro{
  margin-bottom: 60px;
}

.statsBannerCard{
  /* visibility: hidden; */
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.0/ScrollTrigger.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">


<section class="spacer">
  Scroll down
</section>


<section class="statsBanner">
  <div class="container">

    <div class="row">
      <div class="col-12">
        <div class="statsBanner__intro text-center">
          <h2>Start counter when this section is in view.</h2>
        </div>
      </div>
    </div>

    <div class="row justify-content-evenly">


      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="145">145</span>
        </div>
      </div>

      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="Text">Text</span>
        </div>
      </div>

      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="$20,000">$20,000</span>
        </div>
      </div>

      <div class="col-12 col-sm-3">
        <div class="statsBannerCard text-center">
          <span class="statsBannerCard__statistic" data-number="60K+">60K+</span>
        </div>
      </div>



    </div>
  </div>
</section>

SetInterval can’t be stopped by clearInterval when using useEffect

I’ve tried to implement a function that starts a count down when the isPlaying variable is truthy and it stops when it’s falsy, in general, it doesn’t work and all it does is just start multiple intervals simultaneously,
The isPlaying changes when the video stops or start playing again

 let interval
    useEffect(() => {
            if (isPlaying) {
                interval = setInterval(() => {
                    setTimePassed((time) => time + 1)
                }, 1000);
            } else {
                console.log('clear interval');
                clearInterval(interval);
            }
            return () => clearInterval(interval);
        }, [isPlaying])

React Native error Element type is invalid: expected a string

I am using react-native-sass-transformer package with React Native, and I cannot get past the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `App`.

This error is located at:
in RCTView (created by View)
in View (created by ScrollView)
in RCTScrollView (created by ScrollView)
in ScrollView (created by ScrollView)
in ScrollView (created by App)
in App (created by ExpoRoot)
in ExpoRoot
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:149:8 in registerError
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:60:8 in errorImpl
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:34:4 in console.error
at node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:104:6 in reportException
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:172:19 in handleException
at node_modulesreact-nativeLibrariesCoreReactFiberErrorDialog.js:43:2 in showErrorDialog
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:15792:34 in logCapturedError
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:15884:20 in update.callback
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:7199:2 in callCallback
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:7220:20 in commitUpdateQueue
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:16632:25 in commitLifeCycles
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:19216:22 in commitLayoutEffects
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:93:4 in invokeGuardedCallbackProd
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:318:2 in invokeGuardedCallback
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:18952:29 in commitRootImpl
at node_modulesschedulercjsscheduler.development.js:468:23 in unstable_runWithPriority
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:18791:17 in commitRoot
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:18192:12 in performSyncWorkOnRoot
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:5911:33 in runWithPriority$argument_1
at node_modulesschedulercjsscheduler.development.js:468:23 in unstable_runWithPriority
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:5906:23 in flushSyncCallbackQueueImpl
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:5893:28 in flushSyncCallbackQueue
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:17745:30 in scheduleUpdateOnFiber
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:21484:23 in updateContainer
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:22144:17 in render
at node_modulesreact-nativeLibrariesReactNativerenderApplication.js:58:4 in renderApplication        
at node_modulesreact-nativeLibrariesReactNativeAppRegistry.js:117:25 in runnables.appKey.run
at node_modulesreact-nativeLibrariesReactNativeAppRegistry.js:202:4 in runApplication
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:414:4 in __callFunction
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:113:6 in __guard$argument_0
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:365:10 in __guard
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:112:4 in callFunctionReturnFlushedQueue

I have added the code inside metro.config.js and app.json as specified here.

My code inside App.js:

import { ScrollView, StyleSheet } from 'react-native';

import LoginPage from './src/Components/Pages/LoginPage/LoginPage';

export default function App() {
    return (
        <ScrollView style={styles.container}>
            <LoginPage />
        </ScrollView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    }
});

LoginPage.jsx:

import { View } from 'react-native';
const LoginPage = () => {
    return (
        <View></View>
    );
};

export default LoginPage;

Even if I revert the changes made for react-native-sass-transformer, the error persists. I do not have any idea of what to try.

how to update only the file field in model using django rest..i use angular as frontend

I want to update only specific fields in my model. This is my models.py

class CheckinQnResult(models.Model):
    client = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True,related_name='client_create')
    appt = models.ForeignKey(Appointment, null=True, blank=True, on_delete=models.SET_NULL, related_name='appt_qn')
    is_first_visit = models.BooleanField(default=False) 
    document = models.FileField(upload_to='documents', null=True, blank=True)
    duration_of_sickness = models.CharField(max_length=100, null=True, blank=True)
    age_noticed = models.CharField(max_length=100, null=True, blank=True)
    first_sought_age = models.CharField(max_length=100, null=True, blank=True)
    med_treated = models.CharField(max_length=1000, null=True, blank=True)

    

I want to update only specific fields in my model. This is my view.py

              
    class DocumentView(ViewSet):
        model = CheckinQnResult
        serializer_class = DocumentAlldataSerializer
        permission_classes = [IsAuthenticated]
        authentication_classes = [BasicAuthentication, TokenAuthentication, JSONWebTokenAuthentication]
        def create(self,request):
            serializer = self.serializer_class(data=request.data)
            if serializer.is_valid():
                ch_qn = serializer.save()
                appt = Appointment.objects.get(id=request.data.get('appt_id'))
                
                appt.save()
                ch_qn.appt = appt
                ch_qn.save()
                
                return Response({'status': 'success', 'message': 'Check in questions submitted successfully'},
                                status=status.HTTP_200_OK)
                
    
                
            else:
                return Response(serializer.errors)
    
        def getdocument(self,request):
          
            queryset =  CheckinQnResult.objects.filter(client=request.user)
            serializer = DocumentAlldataSerializer(queryset,many=True)
            return Response({'status':'success','data':serializer.data},status=status.HTTP_200_OK) 
           )
        
               
    
        def update(self, request, *args, **kwargs):
            partial = kwargs.pop('partial', False)
            instance = CheckinQnResult.objects.get(id=request.data['id'])
            serializer = self.serializer_class(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            return Response({'status': 'success', 'data': serializer.data}, status=status.HTTP_200_OK)
        
        
        def delete(self, instance):
            instance = CheckinQnResult.objects.get(id=self.request.GET.get('id'))
            instance.delete()
            return Response({'status': 'success', 'message': 'Document Deleted successfully'}, status=status.HTTP_200_OK)

I want to update only specific fields in my model. This is my serializer.py

    
    class DocumentAlldataSerializer(serializers.ModelSerializer):
        appt = AppointmentSerializer()
        client=UserSerializer()
       
        
       
       
        class Meta:
            model = CheckinQnResult
            fields = '__all__'
            extra_fields = ['appt','client']

Here I only want to update the document without affecting other field. When I add other field also, it works but I do not want to add other.

How to update state with react js with componentDidUpdate and setState?

How to update the data with react js eg a user writes a comment how to make this messages show up to all other users?
I used setState in componentDidUpdate with a stop condition but it doesn’t work.
If i don’t make a condition, it work correctely but with infinite loop.

componentDidUpdate(prevProps, prevState) { 
console.log("1" + prevState.changeRepComm.toString())
console.log("2" + this.state.changeRepComm.toString())
 if (prevState.changeRepComm !== this.state.changeRepComm ) {
  if (this.updateTimer) return;     
      this.updateTimer = setTimeout(() => {
      //lister response comments
     fetch('/api/ReponseCommentaire/listerReponseCommentaire', {
      method: "GET",
      headers: {
        'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
        'Content-Type': 'application/json'
      }
    })
      .then(response => response.json())
      .then(response => {
        console.log('Ajouter response:' + JSON.stringify(response))
        this.setState({ ...this.state, reponseCommentaires: response });
      })
      .catch((err) => {
        console.log('fetch failed => ', err);
      })

  }, 1000);

} }

How make url to specific pill bootstrap 5

i’m using bootstrap 5.1 and i’ve got pills tab like:

<div class="d-flex align-items-start">
  <div class="nav flex-column nav-pills me-3" id="pills-tab" role="tablist" aria-orientation="vertical">
    <button class="nav-link active" id="pills-home-tab" data-bs-toggle="pill" data-bs-target="#pills-home" type="button" role="tab" aria-controls="pills-home" aria-selected="true">Home</button>
    <button class="nav-link" id="pills-profile-tab" data-bs-toggle="pill" data-bs-target="#pills-profile" type="button" role="tab" aria-controls="pills-profile" aria-selected="false">Profile</button>
    <button class="nav-link" id="pills-messages-tab" data-bs-toggle="pill" data-bs-target="#pills-messages" type="button" role="tab" aria-controls="pills-messages" aria-selected="false">Messages</button>
    <button class="nav-link" id="pills-settings-tab" data-bs-toggle="pill" data-bs-target="#pills-settings" type="button" role="tab" aria-controls="pills-settings" aria-selected="false">Settings</button>
  </div>
  <div class="tab-content" id="pills-tabContent">
    <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">...</div>
    <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">...</div>
    <div class="tab-pane fade" id="pills-messages" role="tabpanel" aria-labelledby="pills-messages-tab">...</div>
    <div class="tab-pane fade" id="pills-settings" role="tabpanel" aria-labelledby="pills-settings-tab">...</div>
  </div>
</div>

How can i make url to show content of ex. “pills-profile”? if I enter the address for pills in my browser, it will redirect and display it.

Highcharts export button not showing (included the libraries etc)

I have tried several times using other examples available but still no luck
here’s the code https://jsfiddle.net/mrbfqay6/
P.S: you just need to add a random amount in first input field and then click submit to generate graph. Thanks

function renderChart(){

chart = new Highcharts.Chart({

chart: {
  renderTo: 'container',
  type: 'column',
  marginRight: 20,
  events: {
    load: function() {
      // nothing to do here right now
    }
  }
},
title: {
  text: 'Some random data'
},
xAxis: {
  tickPixelInterval: 50
},
yAxis: {
  title: {
    text: 'Value'
  }
},
exporting: {"enabled":true},
tooltip: {
  formatter: function() {
    return '<b>' + this.series.name + '</b><br/>' +
      Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
      Highcharts.numberFormat(this.y, 2);
  }
},
legend: {
  enabled: true
},
exporting: {
  enabled: false
}, plotOptions: {
    column: {
        stacking: 'normal',
      
    }
},
series: [{
name: ' Amortization',
data:amort_data,

 
}
,{
  name: 'Saving',
  data: wow_saving,
  stack:'wow'

},
{
  name: 'Financing',
  data: lease_data,
  stack: 'wow'


}

]
});

}

AWS Amplify config file (aws-export.js) with environment variables (env var)

I am trying to add env file to my, but I get a clientId must be provided.

At the moment, I get “Error: Both UserPoolId and ClientId are required.”

My guess guess is the way I import them. The sequence may not be the most correct OR the script may need something to be able to read the dotenv or digital ocean variables

.env

aws_project_region=us-east-1
aws_cognito_identity_pool_id="us-east-2:aaa-bbbb-cccc-ddd"
aws_cognito_region=us-east-1
aws_user_pools_web_client_id="xxxxxxxxxxxxxxxx"

aws-export.js

const awsmobile = {
  aws_project_region: process.env.aws_project_region,
  aws_cognito_identity_pool_id: process.env.aws_cognito_identity_pool_id,
  aws_cognito_region: process.env.aws_cognito_region,
  aws_user_pools_id: 'us-east-2_yyyyyyyyyyY',
  aws_user_pools_web_client_id: 'yyyyyyyyyyyyyyyyyyy',
  oauth: {},
  aws_cognito_username_attributes: ['EMAIL'],
  aws_cognito_social_providers: [],
  aws_cognito_signup_attributes: ['EMAIL', 'PHONE_NUMBER'],
  aws_cognito_mfa_configuration: 'OFF',
  aws_cognito_mfa_types: ['SMS'],
  aws_cognito_password_protection_settings: {
    passwordPolicyMinLength: 8,
    passwordPolicyCharacters: ['REQUIRES_LOWERCASE', 'REQUIRES_NUMBERS'],
  },
  aws_cognito_verification_mechanisms: ['EMAIL'],
  aws_appsync_graphqlEndpoint:
    'https://hhhhhhhhhhhhh.appsync-api.us-east-2.amazonaws.com/graphql',
  aws_appsync_region: 'us-east-2',
  aws_appsync_authenticationType: 'API_KEY',
  aws_appsync_apiKey: 'da2-ggggggggggggg',
};

export default awsmobile;

_app.tsx

import config from '../../src/aws-exports';

Amplify.configure({
  ...config,
  ssr: true,
});

next.config.js

const withPWA = require('next-pwa');
const runtimeCaching = require('next-pwa/cache');
// https://issueexplorer.com/issue/shadowwalker/next-pwa/288
module.exports = withPWA({
  images: {
    domains: ['live.staticflickr.com', 'c.tenor.com', 'tailwindui.com'],
  },
  pwa: {
    dest: 'public',
    runtimeCaching,
    buildExcludes: [
      /middleware-manifest.json$/,
      /_middleware.js$/,
      /_middleware.js.map$/,
    ],
  },

  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.resolve.fallback = {
      ...config.resolve.fallback, // if you miss it, all the other options in fallback, specified
      // by next.js will be dropped. Doesn't make much sense, but how it is
      fs: false, // the solution
    };

    // SVG fixes
    config.module.rules.push(
      ...[
        {
          test: /.yml$/,
          type: 'json',
          use: 'yaml-loader',
        },
        {
          test: /.svg$/,
          use: '@svgr/webpack',
        },
      ]
    );
    return config;
  },
});

My digital Ocean env variables

https://ibb.co/DbQnwz0

Next.js maintain route when navigating between screens

I have the following problem in Next.js. Im building a Dashboard.
This would be somewhat the root route:

/dashboard/

Here you can select from different Stores to get to the Dashboard of the different stores.
Now when I click on one of the stores, this is my route:

/dashboard/store/%STORE_ID%/

%STORE_ID% is something like 3iHnkdnfkD and I need it to communicate with my backend. Basically I use the ID as one of the keys to my database and wont to get it from the route when clicking on a page. Now, the route goes on… Lets say I have different products and each of them has an ID again:

/dashboard/store/%STORE_ID%/product/%PRODUCT_ID%

When navigating between these individual products, the %PRODUCT_ID% changes obviously and with it the route.
So, I have this route: /dashboard/store/3iHnkdnfkD as example;
The page would now consist of a table where I can click on the products to get a detailed page.
So I would use a NextLink and when I click on one of the products get its id to onclude in the route:

<NextLink href={`/dashboard/store/%STORE_ID%/product/${id}`}>
  <MyUnrelevantButton />
</NextLink>

Now, heres my problem: I need to know the STORE_ID% to navigate to the product, since otherwise, I would lose ref of the store. I know I would be able to retrieve the STORE_ID% from the route and than just pass it in again, but this is redundant and with more than a few NextLinks quite a lot of work. Is there any way to tell Next: Use the route I have right know and just add /product/%PRODUCT_ID% to it

Problem with JQuery Mobile button with onclick

I’m using jquery mobile on a raspberry pi with 7″ Touch display and chromium browser in kiosk mode.

I have serveral Buttons on my page

<button class="ui-btn" onclick="window.location.replace('index.html');">Seite neu laden</button>
<button class="ui-btn" onclick="system('reboot');">System neu starten</button>
<button class="ui-btn" onclick="system('shutdown');">System herunterfahren</button>
<button class="ui-btn" onclick="restart('zway');">Z-Way Server neu starten</button>
<button class="ui-btn" onclick="restart('homebridge');">Homebridge Server neu starten</button>

If i touch the first button the page will be reloaded, but if i touch the last button,
which should call a function, nothing happen.

If i replace the “onclick” (reload the page) from the first button with the “onclick” from the last button (call restart(‘homebridge’)), my function will be called and the homebridge-server will be restarted.

I dont really understand this behaviour. I also tried “ontouchstart” instead of “onclick”.

Do i miss something?

node server not running in browser or in postman in terminal its fine

this is the server.js code

require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const cookieParser = require('cookie-parser')


const app = express()
app.use(express.json())
app.use(cors())
app.use(cookieParser())


//Routes
app.use('api', require('./routes/authRouter'))

const URI = process.env.MONGODB_URL
mongoose.connect(URI, {
    useCreateIndex: true,
    useFindAndModify: false,
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => {
    if(err);
    console.log('Connected to mongodb')
})


const port = process.env.PORT || 5000
app.listen(port, ()=> {
    console.log('server up and running', port)
})

authRouter code

const router = require('express').Router()
const authCtrl = require('../controllers/authCtrl')

router.post('/register', authCtrl.register)

router.post('/login', authCtrl.login)

router.post('/logout', authCtrl.logout)

router.post('/refresh_token', authCtrl.generateAccessToken)


module.exports = router

authCntrl code

const Users = require('../models/userModel')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')

const authCtrl = {
     register: async (req,res) => {
         try {
            const { fullname, username, email, password, gender } = req.body
        console.log(req.body);
        res.json({msg: 'registered'})
     } catch (err) {
        return res.status(500).json({msg: err.message})
     }
 },
 login: async (req,res) => {
    try {
       
    } catch (err) {
       return res.status(500).json({msg: err.message})
    }
},
logout: async (req,res) => {
    try {
       
    } catch (err) {
       return res.status(500).json({msg: err.message})
    }
},
generateAccessToken: async (req,res) => {
    try {
       
    } catch (err) {
       return res.status(500).json({msg: err.message})
    }
}
}

 module.exports = authCtrl

auth router code

const router = require('express').Router()
const authCtrl = require('../controllers/authCtrl')

router.post('/register', authCtrl.register)

router.post('/login', authCtrl.login)

router.post('/logout', authCtrl.logout)

router.post('/refresh_token', authCtrl.generateAccessToken)


module.exports = router

package.json

{
  "name": "web",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.0",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.11.13"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

the thing is that everything seems like its okay but when i open localhost in the browser it doest show
and in postman too
in the terminal it says

server up and running 5000
Connected to mongodb

could be that the dependencies that im using are a bit outdated but im trying to follow a tutorial that was made in January of this year, so i dont want to change the dependencies or update them.

value are not set by the calling function in mocha framework

i have written random function to set some string values in accountname and this is in utilities/random.js. when I try calling this function in my test/sample.js this function is not setting the value of account name

random function

export const randomString = (n) => {
    let str = 'abcdefghijklmnopqrstuvwxyz9876543210';
    let tmp = '',
        i = 0,
        l = str.length;
    for (i = 0; i < n; i++){
        tmp += str.charAt(Math.floor(Math.random() * l));
    }
    return tmp;
}

calling it in test/sample.js

import { randomNum, randomString } from '../utils/random';     
let accountname = randomString(length);

enter image description here

How can I redraw markers in the GoogleMapReact component?

I have a problem with my react google maps component. Even when I switch between different routes and fetch new data, my component won’t refresh markers. I tried to create a state and change it in useEffect to see if the map is rendered again when changing events and it does. So I assume that something needs to be done with the renderMarkers function but I have no idea what, though. I tried console logging markers and they’re displayed only once during application’s first run.

Parent component:

const EventsPage: React.FC<Props> = ({ page_filter }) => {

    const { data: Events_data, isFetching } = useGetEventsQuery(page_filter.toLowerCase());

    return (
        <div className={classes.Main_container}>
            <h2 className={classes.Header}>
                {page_filter} Events:
            </h2>
            <Map data={Events_data} />
            <div className={classes.Events_container}>
                {isFetching && <Loader />}
                {Events_data?.length === 0 ?
                    (
                        <h2>No Events found in this category.</h2>
                    ) :
                    (
                        <Events data={Events_data} />
                    )
                }
            </div>
        </div>
    )
}

Map component (child):

const Map: React.FC<Props> = ({ data }) => {
  const events = data?.events;
  const center = { lat: 51.107, lng: 17.04 };
  const zoom = 14;

  const renderMarkers = (map: any, maps: any) => {
    events?.map(event => {
      const pos = { lat: Number(event.lat), lng: Number(event.lng) };
      let color = "";
      let path = "";

      if (event.type === "Basketball") {
        color = "#dd7e01";
        path = PathType.BASKETBALL
      } else if (event.type === "Volleyball") {
        color = "#2160d4";
        path = PathType.VOLLEYBALL
      } else if (event.type === "Football") {
        color = "#30bf1c";
        path = PathType.FOOTBALL
      } else if (event.type === "Chess") {
        color = "#a88253";
        path = PathType.CHESS
      } else if (event.type === "Tennis") {
        color = "#ceff19";
        path = PathType.TENNIS
      }

      let marker = new maps.Marker({
        position: pos,
        map,
        icon: {
          path: path,
          fillColor: color,
          fillOpacity: 1,
          strokeColor: color,
          scale: 1.15
        },
        title: `${event.type} by ${event.creator.username}. People: ${event.number_of_people}/${event.people_needed}`
      });

      console.log(marker);
    })
  }

  return (
    <div className={classes.Map_container} id={center.toString()}>
      <GoogleMapReact
        bootstrapURLKeys={{ key: {API.key} }}
        defaultCenter={center}
        center={center}
        defaultZoom={zoom}
        margin={[50, 50, 50, 50]}
        // onChange={}
        // onChildClick={}
        onGoogleApiLoaded={({ map, maps }) => renderMarkers(map, maps)}
        options={{
          backgroundColor: "#282C35",
          styles: [
            { elementType: "geometry", stylers: [{ color: "#282C35" }] },
            { elementType: "labels.text.stroke", stylers: [{ color: '#242f3e' }] },
            { elementType: "labels.text.fill", stylers: [{ color: "#746855" }] },
            {
              featureType: "administrative.locality",
              elementType: "labels.text.fill",
              stylers: [{ color: "#E4AD38" }],
            },
            {
              featureType: "transit",
              elementType: "labels.icon",
              stylers: [{ visibility: "off" }]
            },
            {
              featureType: "road",
              elementType: "labels.icon",
              stylers: [
                { visibility: "off" }
              ]
            },
            {
              featureType: "poi",
              stylers: [{ visibility: "off" }],
            },
            {
              featureType: "road",
              elementType: "geometry",
              stylers: [{ color: "#191919" }],
            },
            {
              featureType: "road",
              elementType: "geometry.stroke",
              stylers: [{ color: "#212a37" }],
            },
            {
              featureType: "road",
              elementType: "labels.text.fill",
              stylers: [{ color: "#9ca5b3" }],
            },
            {
              featureType: "road.highway",
              elementType: "geometry",
              stylers: [{ color: "#746855" }],
            },
            {
              featureType: "road.highway",
              elementType: "geometry.stroke",
              stylers: [{ color: "#1f2835" }],
            },
            {
              featureType: "road.highway",
              elementType: "labels.text.fill",
              stylers: [{ color: "#f3d19c" }],
            },
            {
              featureType: "transit",
              elementType: "geometry",
              stylers: [{ color: "#191919" }],
            },
            {
              featureType: "water",
              elementType: "geometry",
              stylers: [{ color: "#17263c" }],
            },
            {
              featureType: "water",
              elementType: "labels.text.fill",
              stylers: [{ color: "#515c6d" }],
            },
            {
              featureType: "water",
              elementType: "labels.text.stroke",
              stylers: [{ color: "#17263c" }],
            },
          ]
        }}

      />
    </div>
  )
}

Can Playwright do conditional test based on the browser that is running it?

I am learning how to use Playwright coming from a Selenium and Cypress background and testing out the tool to see how it performs on a simple test:

test.describe('IMDB:', () => {
    const movieName = 'Forrest Gump';

    await page.goto('https://www.imdb.com/');

    await page.fill('#suggestion-search', movieName);

    expect(await page.textContent('data-testid=search-result--const')).toContain(movieName);
  });
});

It simply goes to IMDB, searches for a movie, and then asserts the movie is found.

I have also created a config file in which I have defined that I want to use multiple browsers:

const config: PlaywrightTestConfig = {
  timeout: 30000,
  use: {
      headless: false
  },
  projects: [
    {
      name: 'Desktop Chromium',
      use: {
        browserName: 'chromium',
        viewport: { width: 1280, height: 720 },
      },
    },
    {
      name: 'Desktop Firefox',
      use: {
        browserName: 'firefox',
        viewport: { width: 1280, height: 720 },
      }
    },
     {
      name: 'Mobile Chrome',
      use: devices['Pixel 5'],
    },
  ],
};

export default config;

However, when I run the test, due to the search bar being hidden behind a button on the mobile site. The Mobile Chrome test fails.

Is there a way I can do conditional testing to say if a particular device is being used, perform an extra step?