#StackBounty: #javascript #reactjs #webpack #lazy-loading #server-side-rendering React Router v5 accompanied with Code Splitting, and D…

Bounty: 100

I have a project where use react-router v3 only for one reason. The reason is the need of server side rendering with data prefetching and the most convenient way to do this is to keep centralized route config in an object or array and loop over the matching elements to fetch the data from the API on the server side. The data later is going to be passed to the client with the response HTML and stored in variable of JSON format string.

Also application uses code splitting, however with the use of babel-plugin-transform-ensure-ignore on sever side I can directly fetch the components instead of lazy loading and the native import method will be used only on client side.

Nevertheless, above-mentioned structure isn’t working with react-router v5, as it’s little bit difficult, since I can’t use @loadable/components, as react-router official documentation suggests. Per my observation @loadable/components just generates the HTML on the server side instead of giving me the components in which I implement the fetch method responsible for server side logic.

Therefore, I would like to ask you the good structure for webpack + react-router v5 + ssr + data prefetch + redux + code splitting

I see it’s quite complicated and no universal solution, however I may be wrong.

Any direction or suggestion is appreciated.


Get this bounty!!!

#StackBounty: #reactjs #typescript #redux #react-redux #mqtt How to best store a complex object of MQTT messages in a React App State?

Bounty: 50

I want to develop a React App with TypeScript, which can store and send MQTT data.

There are a lot of (hundreds) MQTT messages like:
config.laser.enable == "true", config.system.value == "23" or config.user.password == "foobar".

So I end up with an object like:

{
   "config.laser.enable": true,
   "config.system.value": 23,
   "config.user.password": "foobar",
   ...
}

Each of my visual components will use only a small subset of these topics.

My first approach was to create a MQTT client for each component and subscribe to their individual topics, but this seems to be a lot of overhead. So I believe it would be better to have only one MQTT client, which subscribes to everything and stores the message data in a global state.
So my question is: How can I (or shouldn’t I?) store complex data (an object) in a global state in React and making sure that only the components redraw when their specific subset of the global state has changed. Can I use React Redux for this?

Can you give me an example on how to do this?

I am new to React, so please forgive if this is trivial.


Get this bounty!!!

#StackBounty: #javascript #node.js #reactjs #express #sockets Sending data from the client to the server and displaying to the terminal…

Bounty: 50

On the client side, it calls socket.current.emit in useEffect. I am trying to send the name and age to the server and display the data in the server side io.on terminal. I have no error, nothing is displayed in the terminal.

BACKEND

//server.js

const express = require('express');
require('dotenv').config();

const app = express();
const port = process.env.PORT || 8000;

const server = app.listen(port, () => {
    console.log(`connect on the port ${port} - ${process.env.NODE_ENV}`);
});

const io = require('socket.io').listen(server);


io.on('connection', socket => {
    socket.on('hello', data => {
      console.log({name: data.name, age: data.age});
    });
});

FRONTEND

//client

import React, { useState, useRef, useEffect } from 'react';
import io from 'socket.io-client';


const ChatUser = () => {

    const [values, setValues] = useState({
        chatters: [],
        idReceiver: '',
        idSender: ''
    });

    const [activeUser, setActiveUser] = useState('');
    const [message, setMessage] = useState('');
    const [chats, setChats] = useState([]);

    const socket = useRef();
    

    useEffect(() => {

        if(!socket.current) {
            socket.current = io(process.env.REACT_APP_API);
        }

        if(socket.current) {
            socket.current.emit('hello', {name: 'john', age: '23'});
        }
    }, []);


    return (
        <>  

        </>
    );
};

//env
REACT_APP_API=http://localhost:8000/api

Updated backend

My code in server.js Maybe I should put io.on in different place?

const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const db = require('./connection');
const app = express();


// Connect to our Database and handle an bad connections
mongoose
    .connect(process.env.DATABASE, { 
        autoIndex: false
    })
    .then(() => console.log("DB server connect"))
    .catch(() => console.log("DB server disconnect"))


const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const messageRoutes = require('./routes/message');
const countriesRoutes = require('./routes/countries');
const languagesRoutes = require('./routes/languages');
const tutorRoutes = require('./routes/tutor');

app.use(morgan('dev'));
app.use(bodyParser.json({limit: '50mb'}));

app.use((req,res,next)=>{
    res.header('Content-Type: application/json');
    res.header('Access-Control-Allow-Origin','*'); 
    res.header('Access-Control-Allow-Headers','Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods','GET, PUT, POST, DELETE, OPTIONS');
    res.header('Allow','GET, PUT, POST, DELETE, OPTIONS');

    req.io = io;
    next();
});

if(process.env.NODE_ENV === 'development') {

    app.use(cors());

}

const port = process.env.PORT || 8000;

const server = app.listen(port, () => {
    console.log(`connect on the port ${port} - ${process.env.NODE_ENV}`);
});


const io = require('socket.io').listen(server, {
  cors: {
    origin: '*'
  }
});


io.on('connection', socket => {
    socket.on('hello', data => {
      console.log({name: data.name, age: data.age});
    });
});


//middleware
app.use('/api', authRoutes);
app.use('/api', userRoutes);
app.use('/api', countriesRoutes);
app.use('/api', languagesRoutes);
app.use('/api', tutorRoutes);
app.use('/api', messageRoutes);


Get this bounty!!!

#StackBounty: #javascript #reactjs #react-native #listener Update state within listener that is inside useEffect

Bounty: 500

I have a hook called useQueryEvents that 1) fetches all past transactions for a user and 2) listens to the network for incoming/outgoing transactions. In both cases the transactions are passed into a function addActionToActivity that simply appends it to the activity array and updates it in the context state under the key activity.

I can’t get the activity to sync correctly. Whenever the state updates it does not have the last transaction because it’s always one step behind. If I add activity to the dependancy it works but then starts a new listener (due to the whole function being called again with the new activity value) which causes an infinity-like-loop which keeps switching up the state.

function useQueryEvents() {
  const { state: { connectedNetwork, selectedWallet, activity },
  } = useContext(LocalContext);

  useEffect(() => {
    async function bootstrapQueryEvents() {
      // First get all the past transactions
      const transactions = await getAllPastTransactions();
      const contract = await getContract();

      // Now save them to context state via addActionToActivity
      await addActionToActivity(transactions, activity);

      // Now that all the past transactions have been saved
      // listen to all incoming/outgoing transactions and
      // save to context state via addActionToActivity
      contract.on('Transfer', async (from, to, amount, event) => {
        console.log(`${from} sent ${ethers.utils.formatEther(amount)} to ${to}`);
        const transaction = await formatEventToTransaction(event);
        await addActionToActivity(transaction, activity);
      });
    }

    bootstrapQueryEvents();
  }, [selectedAsset, connectedNetwork, selectedWallet]); // <- I've tried adding `activity` here
}

Any ideas how I can approach updating the state while having access to the updated activity value inside the listener without starting a new instance of the listener? Or maybe there’s a different approach I can take altogether?

Thanks in advance


Get this bounty!!!

#StackBounty: #javascript #reactjs #google-analytics TypeError: Illegal Invocation

Bounty: 100

We’re running a Create React App (CRA) web app, to which we’ve added Google Analytics v4. We initiate analytics using the ga-4-react npm package. Manual initialization in index.js

const ga4react = new GA4React(process.env.REACT_APP_GOOGLE_ANALYTICS_ID);

ga4react.initialize().then((ga4) => {
    ga4.pageview(window.location.path);
}, (err) => {
    Sentry.captureException(err);
});

We’re receiving hundreds of errors from the gtag/js file to our Sentry error monitoring platform. This error doesn’t really say much to us and we’ve spent two days trying to find out if anyone’s run into a problem like this, but so far we’ve come up empty. It also doesn’t seem to affect user experience, but it’s rather annoying for us to monitor.

The error is reported as so to Sentry.

TypeError zq(gtag/js)
Illegal invocation

gtag/js in zq at line 477:453
{snip} ))}}},zq=function(a,b,c){var d=a+"?"+b;c?$c.sendBeacon&&$c.sendBeacon(d,c):pd(d)};var Eq=window,Fq=document,Gq=function(a){var b=Eq._gaUserP {snip}

We also receive as many errors from ga-4-react (the catch-block in the code snippet above). We also tried using the analytics snippet with react-helmet, but had the same result.

This error seems to be generated by a number of browsers (Chrome, Opera, Safari, mobile browsers) on many platforms (Android, Windows 10, OS X) so we can’t really pinpoint any specific route, platform, browser that’s common with these users.

I also tried to replicate this with AdBlock, blocking trackers, using Do Not Track, but nothing.


Get this bounty!!!

#StackBounty: #reactjs #webpack #html-webpack-plugin Smart way to handle bundle splitting in React Project

Bounty: 50

My Requirement:
I want to split the main bundle into smaller multiple bundles. When I load a particular page only the bundle associated with that page should get loaded rather than loading all the bundles.

What I have tried:
I tried using html-webpack-plugin to create index.html with multiple bundles used in webpack.
Reference:

  1. https://medium.com/a-beginners-guide-for-webpack-2

I have split entire website functionality in few modules and i have used lazy-loading in my router.js

What Issue I am facing:
I can see 30bundle getting created but on every page load all the 30bundles load.

WEBPACK: I have pasted only html-webpack changes

var HtmlWebpackPlugin = require("html-webpack-plugin");
plugins: [
new HtmlWebpackPlugin({
            filename: "./src/main/webapp/index.html" //relative to root of the application
        })
]

Can anyone suggest what approach I should check/follow?

Thanks !!


Get this bounty!!!

#StackBounty: #node.js #reactjs #nginx #nginx-config #nginx-location How do I Run React App on Nginx with a node.js backend on AWS EC2?

Bounty: 100

I am trying to run a react app with Node.js backend on the Nginx server.

Here’s my server block in the nginx.conf file:

include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/folder-name/frontend/build;
        index index.html index.htm;

        location / {
                proxy_pass http://localhost:5000;
        }
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;



        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

The build folder contains the compiled react js code(using npm run build)
Node.js backend is running on port 5000 using pm2/forever.

After restarting the Nginx Server, the react UI appears on the server IP but the UI is distorted.
Also, I am not able to access my backend APIs on MyIP/api/endpoint.

What am i doing wrong.? This nginx configuration was built from SO and other online resources so there’s a huge probabilty that it could be wrong. Please help!

Thanks in advance!


Get this bounty!!!

#StackBounty: #reactjs #next.js NextJS Back/Forward-button not working in Instagram Inline Safari

Bounty: 100

I have a website using NextJS, wherein all links are using next/link for routing. However, when I visit the website via Instagram inframe Safari, the back-/forward-buttons does not work for the routing. They are grey like I haven’t clicked on a link.

I have tried using

<Link href={blablabla} passHref>
   <a>
      {content}
   </a>
</Link>

But that does not solve the issue. Any thoughts on approach?


Get this bounty!!!

#StackBounty: #javascript #reactjs #react-native How to pass Flatlist items to another screens Flatlist?

Bounty: 50

How do I pass FlatList items to another screen that also have a FlatList?

I’m using React Navigation V5 to pass the FlatList item to the other screen. Thats working fine. I can see the text when only using ´<Text.>{details.id}</Text .>´ but not when trying to pass it to FlatList, then there is nothing.

EDIT: The home screen has clickable FlatList that brings up a Modal. Thats the code below thats inside the modal.

Home screen

const [details, setDetails] = useState('');

<View style={{ flex: 1, backgroundColor: colors.background }}>
      <Modal
        animationType="none"
        hardwareAccelerated={true}
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
          setDetails('');
        }}>
        <View
          style={{
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: 'rgba(0,0,0,0.8)',
          }}>
          <View
            style={{
              backgroundColor: colors.Modal,
              padding: 35,
              borderRadius: 10,
              width: '80%',
              height: '80%',
            }}>
            <ScrollView showsVerticalScrollIndicator={false}>
              <View style={{ marginTop: 20 }}>
                <Text style={{ color: colors.text }}>{details.company}</Text>
                <Text
                  style={{ color: colors.text, marginTop: 20, fontSize: 20 }}>
                  {details.name}
                </Text>
                <Text style={{ color: colors.text, marginTop: 20 }}>
                  {details.gluten}
                </Text>
                <Text style={{ color: colors.text, marginTop: 20 }}>
                  Ingredienser
                </Text>
                <Text style={{ color: colors.text, marginTop: 2 }}>
                  {details.ingredients}
                </Text>
                <Text style={{ color: colors.text, marginTop: 30 }}>
                  {details.id}
                </Text>
              </View>
            </ScrollView>
            <View
              style={{
                borderTopWidth: 1,
                borderTopColor: colors.text,
                marginBottom: 10,
              }}></View>
            <View
              style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
              <Text
                onPress={() =>
                  navigation.navigate('Inköpslista', {
                    details,
                  })
                }>
                Lägg I Inköpslistan
              </Text>
              <TouchableOpacity
                onPress={() => {
                  setModalVisible(false);
                  setDetails('');
                }}>
                <Text style={{ alignSelf: 'center', color: '#FF0000' }}>
                  Stäng
                </Text>
              </TouchableOpacity>
            </View>
          </View>

The screen that i pass the data to

import React from 'react';
import { View, Text, FlatList } from 'react-native';

export default function ShoppingList({ route }) {
  const { details } = route.params;

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        data={details}
        keyExtractor={(details) => details.id}
        renderItem={({ details }) => (
          <View>
            <Text>{details.id}</Text>
          </View>
        )}
      />
    </View>
  );
}

EDIT #2 this is how I open the Modal.

const renderItem = ({ item }) => {
    return (
      <View>
        <TouchableOpacity
          style={{
            marginLeft: 20,
            marginRight: 20,
            elevation: 3,
            backgroundColor: colors.card,
            borderRadius: 10,
          }}
          onPress={() => {
            setModalVisible(true);
            setDetails(item);
          }}>
          <View style={{ margin: 10 }}>
            <Text style={{ color: colors.text }}>{item.company}</Text>
            <Text style={{ color: colors.text, fontWeight: '700' }}>
              {item.name}
            </Text>
            <Text style={{ color: colors.text }}>{item.gluten}</Text>
            <Text style={{ color: colors.text }}>{item.id}</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  };


Get this bounty!!!

#StackBounty: #javascript #python #reactjs #django #digital-ocean How to correctly serve my React production build through Django. Curr…

Bounty: 150

I’m trying to deploy my react/django web-app to a linux-VM droplet. I’m not using a webpack for the JS content. Instead, I’m serving npm run build static files through a CDN sub-domain, digital ocean s3 bucket.

I’m able to python manage.py collectstatic which then pushes my react production build folder to the CDN.

When I visit my production website, it currently just loads up a blank page with these console errors:

Refused to apply style from 'https://www.my_website_URL.com/static/css/main.ce8d6426.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Refused to execute script from 'https://www.my_website_URL.com/static/js/2.ca12ac54.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Refused to execute script from 'https://www.my_website_URL.com/static/js/main.220624ac.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

There aren’t any network errors that provide any useful information for this matter.

The issue has to be server side (django)… I think.


Project set up:

enter image description here

The react production build is inside my core django folder.

Here is how I link my React through django:

core urls.py

def render_react(request):
    return render(request, "index.html") 
    #index.html being created by react, not django templates 
    
urlpatterns = [
   re_path(r"^$", render_react),
   re_path(r"^(?:.*)/?$", render_react),
   ...
]

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    {% comment %} <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> {% endcomment %}
    <link
      rel="stylesheet"
      href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css"
    />
    <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>

    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    

    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

settings.py

import os


from pathlib import Path
from decouple import config
import dj_database_url

from datetime import timedelta

# Build paths inside the project like this: BASE_DIR / 'subdir'.
# BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('DJANGO_SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['URL's']

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_HTTPONLY = True


INSTALLED_APPS = [
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',


    # Third Party Apps #
    'django_filters',
    'corsheaders',
    'django_extensions',
    'drf_yasg',
    'storages',


    # Apps
    'users',
    'bucket',
    'bucket_api',
    
    #oauth
    'oauth2_provider',
    'social_django',
    'drf_social_oauth2',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'oauth2_provider.middleware.OAuth2TokenMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'core.urls'


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS' : [os.path.join(BASE_DIR, 'build')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DJANGO_DB_NAME'),
        'USER' : config('DJANGO_DB_ADMIN'),
        'PASSWORD' : config('DJANGO_ADMIN_PASS'),
        'HOST' : config('DJANGO_DB_HOST'),
        'PORT' : config('DJANGO_DB_PORT'),
        'OPTIONS': {'sslmode':'disable'},
    }
}


db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/New_York'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_ENDPOINT_URL = config('AWS_S3_ENDPOINT_URL')
AWS_S3_CUSTOM_DOMAIN = config('AWS_S3_CUSTOM_DOMAIN')
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
AWS_LOCATION = config('AWS_LOCATION')
AWS_DEFAULT_ACL = 'public-read'


STATIC_URL = '{}/{}/'.format(AWS_S3_ENDPOINT_URL, AWS_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'


STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static/templates'),
    os.path.join(BASE_DIR, 'build/static')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

How can I fix my Django to properly serve production static chunk css and js files from my CDN? The pathing and location to CDN have to be correct if the chrome console is able to locate the files within the error.

Please let me know if you need more information from my side. Currently stuck and do not have a simple solution to fix my MIME type errors and solving my website from loading only a blank page.

Thank you for any help/tips/or guidance!

If anyone is wondering, I’m using Gunicorn and Nginx.

EDIT:
added a bounty to draw attention to this question. I am not using Django webpack loader and babel. I would rather not rely on other libraries that could break things easily.


Get this bounty!!!