Socket io connection not established with express node js, console log does not work

Trying to connect to socket io through a separate chat page tab and not with index.html, but not able to connect. I do not want the chat page to be the home page. Server and client console log does not work either. This only console logs “Express app listening at http://localhost:8888” but not “New WS Connection”.

Server.js

require('dotenv').config();
const express = require('express');
const querystring = require('querystring');
const axios = require('axios');
const port = 8888 || process.env.PORT;

const socketio = require('socket.io');
const cors = require('cors');

const path = require('path');
const http = require('http');

const { addUser, removeUser, getUser, getUsersInRoom } = require('./users');
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server);

app.use(cors());
app.use(router);

io.on('connect', (socket) => {
  socket.on('join', ({ name, room }, callback) => {
    console.log('New WS Connection...');
    const { error, user } = addUser({ id: socket.id, name, room });

    if(error) return callback(error);

    socket.join(user.room);

    socket.emit('message', { user: 'admin', text: `${user.name}, welcome to room ${user.room}.`});
    socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name} has joined!` });

    io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room) });

    callback();
  });

  socket.on('sendMessage', (message, callback) => {
    const user = getUser(socket.id);

    io.to(user.room).emit('message', { user: user.name, text: message });

    callback();
  });

  socket.on('disconnect', () => {
    const user = removeUser(socket.id);

    if(user) {
      io.to(user.room).emit('message', { user: 'Admin', text: `${user.name} has left.` });
      io.to(user.room).emit('roomData', { room: user.room, users: getUsersInRoom(user.room)});
    }
  })
});


server.listen(port, function(){
  console.log(`Express app listening at http://localhost:${port}`);
});

router.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
    res.send('server is up and running');
});

module.exports = router;

chat.js on client side

import React, { useState, useEffect } from 'react'
import queryString from 'query-string';
import io from "socket.io-client";
import './Chat.css';
import InfoBar from '../InfoBar/InfoBar';
import Input from '../Input/Input';
import Messages from '../Messages/Messages';
import TextContainer from '../TextContainer/TextContainer';

let socket;

export default function Chat({ location }) {

    const [name, setName] = useState('');
    const [room, setRoom] = useState('');
    const [message, setMessage] = useState('');
    const [messages, setMessages] = useState([]);
    const [users, setUsers] = useState('');

    const ENDPOINT = 'http://localhost:8888/';

    useEffect(() => {
        const { name, room } = queryString.parse(location.search);

        socket = io(ENDPOINT);

        console.log(name, room);
        setName(name);
        setRoom(room);

        socket.emit('join', { name, room }, (error) => {
            if(error) {
                alert(error);
            }
        });
    }, [ENDPOINT, location.search]);

    useEffect(() => {
        socket.on('message', (message) => {
            setMessages(messages => [...messages, message]);
        });

        socket.on('roomData', ({ users }) => {
            setUsers(users);
        });
    }, []);

   const sendMessage = (event) => {
       event.preventDefault();

       if(message){
        socket.emit('sendMessage', message, () => setMessage(''));
       } 
   }

//    console.log(message, messages);

    return (
        <div className="outerContainer">
            <div className="container">
                <InfoBar room={room}/>
                <Messages messages={messages} name={name}/>
                <Input message={message} setMessage={setMessage} sendMessage={sendMessage} />
            </div>
            <TextContainer users={users} />
        </div>
    );
}

How to filter a GraphQL query to pull data and fields from two tables?

I am very new to GraphQL, and am struggling to get the correct data returned to me when I execute the GraphQL query I created.

Starting at the top, I have 3 tables or models: UserTB, UserRoleTB, and RoleTB.

  • UserTB holds a list of all created users. One to many relationship with UserRoleTB
  • UserRoleTB holds a list of all Users and their assigned Roles
  • RoleTB holds a list of all roles. One to Many relationship with UserRoleTB

Table Schemas:

type UserRoleTB @model @auth(rules: [{allow: public}]) {
  id: ID!
  roletbID: ID! @index(name: "byRoleTB")
  usertbID: ID! @index(name: "byUserTB")
}

type RoleTB @model @auth(rules: [{allow: public}]) {
  id: ID!
  roleName: String
  roleDescription: String
  UserRoleTBS: [UserRoleTB] @hasMany(indexName: "byRoleTB", fields: ["id"])
}

type UserTB @model @auth(rules: [{allow: public}]) {
  id: ID!
  username: String
  name: String
  email: String
  password: String
  lastLogin: String
  UserRoleTBS: [UserRoleTB] @hasMany(indexName: "byUserTB", fields: ["id"])
}

I created two queries that will return all data from the UserRoleTB and the UserTB.

Queries:

export const listUserTBS = /* GraphQL */ `
  query ListUserTBS(
    $filter: ModelUserTBFilterInput
    $limit: Int
    $nextToken: String
  ) {
    listUserTBS(filter: $filter, limit: $limit, nextToken: $nextToken) {
      items {
        id
        username
        name
        email
        password
        lastLogin
        createdAt
        updatedAt
        _version
        _deleted
        _lastChangedAt
      }
      nextToken
      startedAt
    }
  }
`;
export const listUserRoleTBS = /* GraphQL */ `
  query ListUserRoleTBS(
    $filter: ModelUserRoleTBFilterInput
    $limit: Int
    $nextToken: String
  ) {
    listUserRoleTBS(filter: $filter, limit: $limit, nextToken: $nextToken) {
      items {
        id
        roletbID
        createdAt
        updatedAt
        _version
        _deleted
        _lastChangedAt
      }
      nextToken
      startedAt
    }
  }
`;

I need to apply a filter to these where if users have a specific role assigned to them, it returns that user. For example, I will run the listUserRoleTBS query and apply a filter that does just that:

query Example {
  listUserRoleTBS(filter: {roletbID: {eq: "0f16af1f-007d-4a46-b6c1-799539ac1a0f"}}) {
    items {
      usertbID
    }
  }
}

which returns the following:

{
  "data": {
    "listUserRoleTBS": {
      "items": [
        {
          "usertbID": "b0e294de-32cb-4fa4-8ca8-c42cb191d26f"
        },
        {
          "usertbID": "22bda12a-8399-458d-9b15-0e83864125b5"
        },
        {
          "usertbID": "89f9c1c4-fa5a-44da-b245-e5add7abd436"
        }
      ]
    }
  }
}

In addition to the displaying the usertbID, I also need to display the name field from the UserTB table. However, it doesn’t seem possible since it does not belong to the UserRoleTB table. It appears I may only be able to use the PK of the UserTB table (usertbID) as an option for response. Having the name field in the response is important because that field will be used to populate a drop-down list on a front-end GUI

Is there any way I can add the name field from UserTB to this query? If not, what are my options?

Additionally, I tried a different approach where I run the listUserTBS query with the following filter:

query Example {
  listUserTBS {
    items {
      name
      UserRoleTBS(filter: {roletbID: {eq: "0f16af1f-007d-4a46-b6c1-799539ac1a0f"}}) {
        items {
          roletbID
        }
      }
    }
  }
}

and it provided the following result:

{
  "data": {
    "listUserTBS": {
      "items": [
        {
          "name": "Joe",
          "UserRoleTBS": {
            "items": [
              {
                "roletbID": "0f16af1f-007d-4a46-b6c1-799539ac1a0f"
              }
            ]
          }
        },
        {
          "name": "brandon",
          "UserRoleTBS": {
            "items": [
              {
                "roletbID": "0f16af1f-007d-4a46-b6c1-799539ac1a0f"
              }
            ]
          }
        },
        {
          "name": "glen",
          "UserRoleTBS": {
            "items": [
              {
                "roletbID": "0f16af1f-007d-4a46-b6c1-799539ac1a0f"
              }
            ]
          }
        },
        {
          "name": "dave",
          "UserRoleTBS": {
            "items": []
          }
        },
        {
          "name": "stewart",
          "UserRoleTBS": {
            "items": []
          }
        }
      ]
    }
  }

As you can see, it will give me every user within the system, and if a user has the specified role, it will display the role. However, the downside is it will fetch literally ever user even if they don’t have the role. I don’t need every user, just a subset.

Javascript, sorting with negatives, please explain why negatives don’t sort? [duplicate]

Trying to write a simple function to sort an input string of numbers:

function highAndLow(numbers){
  let splitNums = numbers.split(" ");

  let negArr =[];
  let posArr = [];
  
  for(let c=0; c<splitNums.length;c++){
    if (splitNums[c][0] == '-'){
      negArr.push(splitNums[c]);
    }
    else{
      posArr.push(splitNums[c]);
    }
  }

  
  let negSorted = negArr.sort();
  let posSorted = posArr.sort();
  
  let lowest = negSorted.slice(-1);
  let highest = posSorted.slice(-1);
  let arr = [(lowest + ' ' + highest).toString()];
  console.log(arr);

  return(arr);
 
}

highAndLow('-30, -10, -9, -8, -4, 0, 1, 4, 6, 7, 20');

further, something like the following evaluates as true and prints to console…. why??:

if('-30'>'-10'){
  console.log('true');
}

Updating Next.js App Components After User Login

I have a static 2-page Next.js app that I want to integrate a user-based system with. I’ve decided to use Auth0 for authentication. My goal is to let a user see documents that they have saved on my app, similar to Grammarly, but I am not sure how the entire UI will conditionally change after the user has logged in.
For example, think about the NavBar, which is a component in my app named navbar.js.

import Link from "next/link";
export const siteTitle = "Title";
export const siteDescription = "Description";

export default function Navbar({ page, ...props }) {
  return (
    <nav className="navbar navbar-expand-lg navbar-light bg-white">
      <div className={page == "page1" ? "container-fluid" : "container"}>
        {/* <!-- Toggle Open --> */}
        {page == "Page1" || (
          <button
            className="navbar-toggler"
            type="button"
            data-toggle="collapse"
            data-target="#navbarCollapse"
          >
          </button>
        )}

        {/* <!-- Collapse --> */}
        <div className="collapse navbar-collapse" id="navbarCollapse">

          {/* <!-- Toggle Close --> */}
          <button
            className="navbar-toggler"
            type="button"
            data-toggle="collapse"
            data-target="#navbarCollapse"
          >
          </button>

          {/* <!-- Buttons --> */}
          {page == "Page1" ? (
            ""
          ) : (
            <Link href="/page1">
              <a className="navbar-btn">
                Page 1
              </a>
            </Link>
          )}
          {page == "Link1" ? (
            ""
          ) : (
            <Link href="https://link2">
              <a className="secondary-navbar-btn">
                Link 1
              </a>
            </Link>
          )}
        </div>
      </div>
    </nav>
  );
}

Considering that the navbar will changing after login, (I want to have “documents” that the user can save directly and later access, meaning that a “My Documents” button must appear in the navbar after login) I am unsure of how the navbar.js file should now be written. Should I just created a new component that will be used after login; if so how would that look? Or should those extra buttons be added in my original navbar.js file, but only rendered after login? Are there existing react hooks that modify components depending on login status?

I would greatly appreciate any links to documentation or tutorials that are solving a problem similar to mine, since I have been unable to find these resources on my own.

Why is the in my if statement affecting another div although they have no relation?

I am creating a Pong game using JS and HTML, there are two paddles (player1 and player2), the If satement starting on line 11 dictates the movement of the paddles.

However, when I move the first paddle, the second paddle moves as well although they have different controls, I cannot seem to figure out why this is happening

The HTML

    <!DOCTYPE html>
    <html> 
        <head>
            <link rel = "stylesheet" href = "pong.css"> </link>
                
        </head> 

        <body>
                <div id = "gameArena">  
                <div id = "player1"> </div> <div id = "player2"> </div>
                
                </div>

        </body>
        <script src = "pong.js"> </script>

    </html> 

The JS:

**    // Important Variables to declare 
    let paddle1 = document.getElementById("player1")
    let paddle2 = document.getElementById("player2")
    let paddlepos1 = 250
    let paddlepos2 = 250 

    //Event Listener 
    // Paddle 1: (W to move up, S to move down)
    //Paddle 2: (UpArrow to move up, down arrow to Move down)
    document.addEventListener('keydown', function (event){
        if(event.keyCode == 87){
            //Move Paddle 1 Up 
            paddlepos1 -= 10 
            paddle1.style.marginTop = paddlepos1 + "px"
        } 
        else if (event.keyCode == 83){
            //Move Paddle 1 Down
            paddlepos1 += 10 
            paddle1.style.marginTop = paddlepos1 + "px"
        } else if  (event.keyCode == 38){
            // paddle 2  up 
            paddlepos2 -= 10  
            paddle2.style.marginTop = paddlepos2 + "px"
        } else if (event.keyCode == 40){
            //paddle 2 down 
            paddlepos2 += 10
            paddle2.style.marginTop = paddlepos2 + "px"
        }
    }





    )




    //ading pixels means that the paddle will go DOWN 
**

The CSS:

        #gameArena{
            width: 500px;
            height: 500px;
            border: 1px solid black;
            align-self: auto;
            margin: auto;
            background-color:green
        }

        #player1{
            width: 10px;
            height: 100px;
            border: 1px solid black;
            background-color: white;
            margin-left:10px;
            margin-top: 250px;
            
        }

        #player2{
            width: 10px;
            height: 100px;
            border: 1px solid black;
            background-color: white;
            margin-left: 480px;
            margin-top: -250px;
            
        }

How to fix MIME errors on refresh when using URL parameters

I don’t know if I will be able to explain good enough but..
I have a setup like this

page(navigationMiddleware);

page('/', homeView);
page('/login', loginView);
page('/register', registerView);
page('/movies', catalogView);
page('/create', createView);
page('/search', searchView);
page('/movies/:movieId', detailsView);
page('/movies/:movieId/edit', editView);
page('/watch/:movieId', watchView);
page('*', notFoundView);

All pages work fine if I don’t refresh the page. All pages without params after their route work fine even after refresh – everything renders perfectly.
But when I am at any page with params on it (e.g. movies/idOfItem) and I try to refresh the page I get this error

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type checking is enforced for module scripts per HTML spec.

And my page does not render.. My guess is that it loses the params?? when I refresh and can’t render it because of that. But then how can I fix that? I don’t know what the actual problem is. I hope someone can answer this.

I’ve got this error many times before, but it usually is because of wrong import paths or using something from page.js the wrong way, this might be the case here, but I don’t know what to do..

I tried to write in javascript for the first time today and everything i see online leads me to believe this should work, but no [duplicate]

var num1 = window.prompt('what is the first number?');

  var num2 = window.prompt('what is the second number?');

  var ope = window.prompt('what is the desired operation?');

  num1 = parseFloat(num1)

  num2 = parseFloat(num2)

  if (ope = '*'){
      var ans = num1 * num2
      document.write(ans);
  }
  else if (ope = '/'){
      var ans = num1 / num2
      document.write(ans);
  }
  else if (ope = '+'){
      var ans = num1 + num2
      document.write(ans);
  }
  else if {
      var ans = num1 - num2
      document.write(ans);
  }

its incredibly simple and I cant get it to work for the life of me, even though it seems to follow proper syntax nothing even shows on screen. not even the prompts

The projectile is not dealing (if not) any damage to the enemy. How do I fix?

I am trying to get a shooter game going where the user pushes space that launches a ball and it goes to the enemy. If it hits the X and Y or whatever of the enemy, the health should subtract. It only seems to deal damage once and not update the innerHTML:

This is the js:

window.alert("Base speaking: The madbiker is trying to escape.");
window.alert("That blasted lunatic always messes things up! Stop him at once!");
window.alert("And click on the screen if you want background music.");
let musicOff = true;
window.addEventListener("click", function(){
    if(musicOff){
    document.getElementById("chaseTheme").play();
    musicOff = false;
    }
});
var madBikerHealth = parseInt(document.getElementById("bossHealth").innerHTML);
var playerHealth = parseInt(document.getElementById("playerHealth").innerHTML);
document.addEventListener("keydown", move);
function move(e){
    if(e.keyCode == 39 || e.keyCode == 68){
        let target = document.getElementById("chopperGuy");
        let size = parseInt(target.style.left) + 20;
        target.style.left = size;

    }
    if(e.keyCode == 37 || e.keyCode == 65){
        let target = document.getElementById("chopperGuy");
        let size = parseInt(target.style.left) - 20;
        target.style.left = size;
    }
}
document.addEventListener("keydown", fire);
function fire(e){
    if(e.keyCode == 32){
        e.preventDefault();
        e.stopPropagation();
        let c = document.createElement("img");
        c.className = "ball";
        c.src = "projectile.png";
        document.body.appendChild(c);
        let madBiker = document.getElementById("madBiker");
        let madBikerX = parseInt(madBiker.style.left);
        madBiker.style.left = madBikerX;
        // let madBikerY = parseInt(madBiker.style.top);
        // madBiker.style.top = madBikerY;
        
        let shift = parseInt(document.getElementById("chopperGuy").style.left) + 100;
        c.style.left = shift;
        c.style.display = "block";
        c.style.animation = "fire";
        // let positioning = parseInt(document.getElementById("chopperGuy").style.top);
        // c.style.top = positioning;
        c.style.animationDuration = "1s";
        if(parseInt(c.style.left) == parseInt(madBikerX)){
            let healthMinus = Math.floor(Math.random() * 5) + 1;
            madBikerHealth.innerHTML = madBikerHealth - healthMinus;
            console.log (madBikerHealth);
        }
        setTimeout(()=>{
            c.parentNode.removeChild(c);
        }, 1000);
    }
}
if(parseInt(madBikerHealth) == 0){
    window.location.href = "../cutscene3/cutscene3.html"
}
function madBikerMoving(){
setInterval(()=> {
let madBiker = document.getElementById("madBiker");
madBiker.style.animation = "moving";
madBiker.style.animationDuration = "3s";
madBiker.style.animationFillMode = "forwards";
madBiker.style.animationIterationCount="infinite";
}, 1000/60);
}
madBikerMoving();

The HTML looks like this:

<html>
    <div>
        <img src = "Background.gif" position = "fixed" id = "road" width= 50% length= 50%>
 
        <p id = "objective">Use A to move left and D to move right (or the left and right arrow keys. Use space to shoot
            Stop the mad biker! Watch out! He has exhaust guns he can shoot at you! Dodge them!</p>

        </div>
        <div>
            <p id = "madBikerHealth">MadBiker Health:</p>  <p id = "bossHealth">250</p>
        </div>
        <div>
            <p id = "YourHealth">Your health:</p> <p id = "playerHealth">250</p> 
        </div>
    <script defer src = "bossfight1.js"></script>
    <link href = "colors.css" rel = "stylesheet">
    <body width>
        <div id = "image1">
            <img src = "chopperGuyPOV.gif" id = "chopperGuy" style = "top: 500px;
            left: 500px;">
        </div>
        <div id = "image2">
            <img src = "madBikerFromBehind.gif" id = "madBiker" style = "top: 300px;
            left: 300px;">
        </div>
        <img src = "projectile.png" class = "ball">
        <div id = "music">
            <audio id = "chaseTheme" src = "chasetheme.mp3" autoplay></audio>
        </div>
    </body>
</html>

And the CSS looks like this:

#chopperGuy{
   width: 200px;
   height: 200px;
   position: absolute;
}

#madBiker{
   width: 70px;
   height: 70px;
   position: absolute;
}

body{
   background-color: black;
}


#YourHealth{
   font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
   color: blue;
   text-align: right;
   position: absolute;
   top: 100px;
   left: 750px;
}
#madBikerHealth{
   font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
   color: blue;
   text-align: right;
   position: absolute;
   top: 200px;
   left: 750px;
}

#playerHealth{
   font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
   color: blue;
   text-align: left;
   position: absolute;
   top: 100px;
   left: 850px;
}
#bossHealth{
   font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
   color: blue;
   text-align: right;
   position: absolute;
   top: 200px;
   left: 900px;
}

.ball{
   display: none;
   width: 20px;
   height: 20px;
   position: absolute;
}

@keyframes moving {
   33%{
      top: 300px;
      left: 200px;
   }
   66%{
      top: 300px;
      left: 400px;
   }
   100%{
      top: 300px;
      left: 300px;
   }
   
}

@keyframes fire{
   10%{
      top: 400px;
      /* left: 500px; */
   }
   100%{
      top: 300px;
      /* left: 500px; */
   }
}

How to use correctly reduce()? Convert date year from months

I want to display on chart 3 values. The problem is that chart1 contains 25elements representative each year, and chart2 and chart3 container 300 elements representative each month. It is the same, but is not.
To show it on graph I need to have these value on the same ground.

the more sens have is adding each elements of chart 2 and chart 3, to self, to have just 25 elements.

I read that reduce() can adding each other elements to self, so it is one step forward to my goal but do not understand this function.

I started then with adding chart1 and I failed. I did something like that:

var months = []
for(var i= 0; i< chart1.length; I++){
var month = chart1[I]/12;
var months[0] = month;
var months[1] = month;
...
var moths[11] = month;
} 

and then wanted it flat (because I imagine it as months = [[1,2,3],[1,2,3]…] and sort and display, but noting was show…

btw.

chart1 looks like

1st year: 1000;
2nd year: 1002;
4rd year: 1004,5;

chart2 is 300 copies of one value

For look skips characters in input :/

I don’t know why this is happening. Can someone please shed some light on this? I’m trying to go through all characters in variable input but it keeps skipping letters for some reason. Anyone know why? I set brerakpoints in the browser, but that just proves that letters are being skipped.

the output shouold be something liek:

-
>
o
... and so on.

But instead it’s something like this:

-
main.js:20 - 
main.js:20 - u
main.js:20 - u 
main.js:20 - u i
main.js:20 - u ih
reader = function(input) {
    var builtString = "";
    var isAssigning = false;
    var previousCharacter = "";
    var currentCharacter = "";
    var nextCharacter = "";
    var found = "";

    for(var index = 0; index < input.length; index++) {
        previousCharacter = input[index];
        currentCharacter = input[index];
        nextCharacter = input[index++];
        
        builtString += currentCharacter;

        console.log(builtString);

        // It could be an action operator.
        if(builtString == "->") {
            console.log(builtString);
        }
    }
}

Get json data to $router.push in Vue.js?

im new on js, and i try to create a router from my backend /user-info where his store all informations from the current user :

enter image description here

Now, i wanted to find a mean to handle each information to use that on my Vuejs Dashboard, i used axios for that, so this is what i made for index.js:

const express = require('express')
const router = express.Router()
const { ensureAuth, ensureGuest } = require('../middleware/auth')
const axios = require('axios')


router.get('/user-info', ensureAuth, async (req, res) => {
   try {
     let uri = 'http://localhost:5000/user-info';
     res.json(`userInfo : ${req.user}`);
     this.axios.get(uri).then((response) => {
     this.$router.push({name:'Dashboard'});

   } catch (err) {
     console.error(err)
     res.render('error')
    }
 })

…and what i did for my Dashboard.vue :

<template>
  <div class="customers container">
  <h1 class="page-header">Welcome to your dashboard</h1>
  <table class="table table-striped">
   <thead>
    <tr>
     <td>{{user.image}}</td>
     <td>{{'Hello' user.displayName}}</td>
     <<td>{{user.email}}</td>
     <th></th>
    </tr>
   </thead>
 </table>

</div>
</template>
<script>
export default {
name: 'dashboard',
data () {
return {
    user: [],

  }
},

methods: {
getUserInfo(){
  this.$http.get('http:localhost:5000/user-info')
    .then(function(response){

    this.user = (response.body); 
   });
  }
 </script>

Unfortunately i got nodemon :

[nodemon] app crashed - waiting for file changes before starting...

Passing array to useState [duplicate]

I am fetching an API which returns an array of objects then trying to pass that array of object into a useState. When logging out the variable holding my API request, everything works fine. However when setting my useState to the variable holding my API request (an array of objects) and console.logging my useState, I am getting [Object Object].

However, when I create a local array and try to pass it into the useState object, I have no problem outputting it when console.logging my useState.

So my question is, how would I pass a fetched array to my useState so that I am able to console.log it out.

Thanks

 import React from "react";

    import { useState, useEffect } from "react";
    
        export default function Genrenavbar() {
          const [mygenres, setMygenres] = useState([]);
        
          useEffect(() => {
            async function APIrequests() {
              const response = await fetch(
                `https://api.themoviedb.org/3/genre/movie/list?api_key=<<MYAPIKEY>>&language=en-US`
              );
              const movie = await response.json();
              console.log(movie);
              setMygenres([movie]);
              console.log("state log " + mygenres);
            }
            APIrequests();
          }, []);
            
          return (
            <div>
              <h1>Hello</h1>

Below is what I am getting when I log out movie (the variable holding the API request) – this is correct

{genres: Array(19)} genres: Array(19) 0: {id: 28, name: ‘Action’} 1: {id: 12, name: ‘Adventure’} 2: {id: 16, name: ‘Animation’} 3: {id: 35, name: ‘Comedy’} 4: {id: 80, name: ‘Crime’} 5: {id: 99, name: ‘Documentary’} 6: {id: 18, name: ‘Drama’} 7: {id: 10751, name: ‘Family’} 8: {id: 14, name: ‘Fantasy’} 9: {id: 36, name: ‘History’} 10: {id: 27, name: ‘Horror’} 11: {id: 10402, name: ‘Music’} 12: {id: 9648, name: ‘Mystery’} 13: {id: 10749, name: ‘Romance’} 14: {id: 878, name: ‘Science Fiction’} 15: {id: 10770, name: ‘TV Movie’} 16: {id: 53, name: ‘Thriller’} 17: {id: 10752, name: ‘War’} 18: {id: 37, name: ‘Western’} length: 19

This is what I get when I log out mygenres (The useState that I am trying to put the variable movie in)

state log [object Object]

How to make NextJS inject styles inline in production?

By default, NextJS will inject <style> tags inline inside head in development (possibly using style-loader under the hood).

In production mode, NextJS will extract css chunks and serve them as separate css files from _next/static directory.
I debugged webpack config NextJS serves by default and noticed it uses mini-css-extract-plugin under the hood to achieve this behavior.

The problem is, for my needs I need NextJS to inject inline styles in production as well. What is the easiest way to achieve this without crazy webpack config modifications?

Here is the current next.config.js that I use

const nextConfig = {
    useFileSystemPublicRoutes: false,
    poweredByHeader: false,
    assetPrefix: '',
    webpack(config) {
        console.dir(config.module.rules, { depth: null, colors: true });
        config.module.rules.push({
            test: /.svg$/,
            use: ['@svgr/webpack'],
        });

        return config;
    },
};

module.exports = nextConfig;