Failed to fetch dynamically imported module:

I have a few components that are lazy imporent in App.tsx that is used in Index.tsx where it is randered and appended to the body.

   const IndexPage = lazy(() => import("../features//IndexPage"));
    const TagsPage = lazy(
      () => import("../features/tags/TagsPage")
    );
    const ArticlePage = lazy(() => import("../features/article/ArticlePage"));

    const SearchResultPage = lazy(
      () => import("../features/search-result/SearchResultPage")
    );

    const ErrorPage = lazy(() => import("../features/error/ErrorPage"));

    ----

    <BrowserRouter basename={basename}>
      <Suspense fallback={<Fallback />}>
        <Routes>
          <Route path={INDEX} element={<IndexPage />} />
          <Route path={ARTICLE} element={<ArticlePage />} />
          <Route path={TAGS} element={<TagsPage />} />
          <Route path={SEARCH} element={<SearchResultPage />} />
          <Route path={ERROR} element={<ErrorPage />} />
          <Route path="/*" element={<ErrorPage />} />
        </Routes>
      </Suspense>
    </BrowserRouter>

Often, the following error happens on production.

Failed to fetch dynamically imported module:

https://help.example.io/tags/static/js/SearchResultPage-c1900fe3.js

I have changed the build path. Therfore, it is tags/static/js.

Does someone know how to fix this issue?

Why var value is being updated in a function that only updates the parameter? – Job Application test Question

Here, i have some doubts with this piece of code i found in a job application test i made a few hours ago.

function foo(x){
    x['key'] = "new value"
}

var a = {'key': "old value"}

foo(a)

console.log (a)
  • Why is the a.key being updated when im just asigning a new value to
    the function parameter not to the global var?

Fiddle JS:
https://jsfiddle.net/SoujiCode/gu2xcwe6

Rest of function is firing before value is resolved, async / await [closed]

As title says, I am trying (and failing) to make the for loop wait until data is resolved before the loop is fired, unfortuntely I’m stuck!

function getPots() {

    fetch(`${uri}/postpot`)
        .then(response => response.json())
        .then(data => {
         return data;
     })
        .catch(error => console.error('Unable to get items.', error));
}

async function displayPots() {

    const potLists = document.getElementsByClassName("potLists");

    var data = await getPots();

   //for loop goes here
}

TypeError: Cannot read properties of null (reading ‘useContext’)

While going to route / or /news in terminal this error occurs (this is a next.js project)

Warning: Invalid hook call. Hooks can only be called inside of the body of a 
function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and 
fix this problem.
TypeError: Cannot read properties of null (reading 'useContext')
 at Object.useContext (/media/jahid/SSD Remaining/Running 
 Projects/WEB/Youtube/Next.js Crash Course for Beginners 2021 - Learn NextJS from Scratch in this 100% Free Tutorial/1/nextjs-course/node_modules/react/cjs/react.development.js:1616:21)
at Head (/media/jahid/SSD Remaining/Running Projects/WEB/Youtube/Next.js Crash Course for Beginners 2021 - Learn NextJS from Scratch in this 100% Free Tutorial/1/nextjs-course/node_modules/next/dist/shared/lib/head.js:176:34)
at renderWithHooks (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5471:16)
at renderIndeterminateComponent (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5544:15)
at renderElement (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5759:7)
at renderNodeDestructive (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5898:11)
at renderNode (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:6030:12)
at renderChildrenArray (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5986:7)
at renderNodeDestructive (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:5918:7)
at renderNode (/usr/local/lib/node_modules/next/node_modules/react-dom/cjs/react-dom-server.browser.development.js:6030:12)

While in console it occurs

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
:3001/:1 GET http://localhost:3001/_next/static/chunks/fallback/webpack.js?ts=1653469342780 net::ERR_ABORTED 500 (Internal Server Error)
:3001/:1 GET http://localhost:3001/_next/static/chunks/fallback/main.js?ts=1653469342780 net::ERR_ABORTED 500 (Internal Server Error)
:3001/:1 GET http://localhost:3001/_next/static/chunks/fallback/pages/_app.js?ts=1653469342780 net::ERR_ABORTED 500 (Internal Server Error)
:3001/:1 GET http://localhost:3001/_next/static/chunks/fallback/pages/_error.js?ts=1653469342780 net::ERR_ABORTED 500 (Internal Server Error)
:3001/:1 GET http://localhost:3001/_next/static/chunks/fallback/react-refresh.js?ts=1653469342780 net::ERR_ABORTED 500 (Internal Server Error)
:3001/favicon.ico:1 GET http://localhost:3001/favicon.ico 500 (Internal Server Error)

index.js

export default function HomePage() {

    return <h1>The Home Page</h1>
}

news.js

export default function NewsPage() {
   return <h1>The News Page</h1>
}

React search for an element from map function and scroll to that location

I am trying to search an element from a map function and scroll to the location of that element –

const time = “1235”

return <RightWrapper>
    
    {arr.map((transcript) => (
  <p
    dangerouslySetInnerHTML={createMarkup(transcript)}
    key={transcript.id}
    
  ></p> </RightWrapper>

Here I want to search for value time(which in this case is 12345) in transcript and scroll to that part when there is a match.

Attempt to get token returns undefined

I’m using an API with javascript to make a login and, the login is working, but now, I need to make the logout and I need to get the token from the success message that appears on the console like this:

{"access":1,"message":"Success!","status":200,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjQyLCJ1c2VybmFtZSI6ImJlcm5hcmRvIiwiYWNjZXNzX21vZGUiOjEsImV4cCI6MTY1MzQ3Mjk0NX0.lf6KgIF7FSjKFhPyRvOplYxgq3DLHEbDiRgHhH_oOWY","uid":42,"username":"bernardo"}

But when I tried to get the token on my fetch like this:

 fetch("https://api.secureme.pt/api/v1/auth/login", requestOptions)
        .then((response) => response.text())
        .then((result) => console.log(result.token)) <-- HERE
        .catch((error) => console.log("error", error));

It returns undefined and I don’t know why.

How can I control chrome with javascript?

I can control with right click,inspect and console a webpage.But,When the web page is refreshed, the javascript codes I wrote in the console are not valid.
So,I want to control chrome from a fixed javascript console window.The javascript codes I write should work not only on one website, but also on all websites.
Can you help me?

Why am I getting a Firebase INVALID_DYNAMIC_LINK_DOMAIN error?

I tried to add email verification in my React website but nothing seems to be working. When I initiate the sendSignInLinkToEmail function, it returns this error:

XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=xxxxxxxxxxxxxxxxxxx
[HTTP/3 400 Bad Request 487ms]

{
  "error": {
    "code": 400,
    "message": "INVALID_DYNAMIC_LINK_DOMAIN",
    "errors": [
      {
        "message": "INVALID_DYNAMIC_LINK_DOMAIN",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

Code in question:

export const registerWithEmailAndPassword = async (name, email, password) => {
  try {
    await sendSignInLinkToEmail(auth, email, actionCodeSettings)
      .then(() => {
        // The link was successfully sent. Inform the user.
        // Save the email locally so you don't need to ask the user for it again
        // if they open the link on the same device.
        window.localStorage.setItem("emailForSignIn", email);
        console.log("test");
        // ...
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ...
      });
      
    const res = await createUserWithEmailAndPassword(auth, email, password);
    const user = res.user;
    await addDoc(collection(db, "users"), {
      uid: user.uid,
      name,
      authProvider: "local",
      email,
    });
  } catch (err) {
    console.error(err);
    alert(err.message);
  }
};

actionCodeSettings:

const actionCodeSettings = {
  // URL you want to redirect back to. The domain (www.example.com) for this
  // URL must be in the authorized domains list in the Firebase Console.
  url: "https://MYIPADDRESS:3000/",
  // This must be true.
  handleCodeInApp: true,
  iOS: {
    bundleId: "com.example.ios",
  },
  android: {
    packageName: "com.example.android",
    installApp: true,
    minimumVersion: "12",
  },
  dynamicLinkDomain: "https://MYIPADDRESS:3000/",
};

The problem probably lies in the actionCodeSettings, I want my website to redirect to root after performing the registration. By the way, I am locally hosting this website, it is not public, that’s why I added my ip address for the url. I have also added my ip to the authorized urls in Firebase. Also registration is on MYIPADDRESS:3000/register

Thanks in advance!

Create 3d image hover effect

I want to create this effect but with javascript not in pure css as he did. And no scss also just css It’ll be good. codepen

.picture-container {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  justify-self: center;
  align-items: center;

  width: 40%;
  height: 100vh;
}
.picture-frame {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;

  padding: 5%;

  border: solid 1px #000;
}
.picture {
  z-index: 1;
  width: 100%;
  height: 100%;
}
<html>
<div class="picture-container first-picture horizontal-small">
          <div class="picture-frame">
            <img
              id="secondPic"
              src="https://picsum.photos/200/300"
              alt="picture of a brick house"
              class="picture middle-right"
            />
         </div>
</div>
<html>

I’m also using Vuejs if it changes something for this

Adding PROPS Data into the API body and Display the Response

I have a simple react application.

When a user clicks on Pay button. It posts data to my API and returns form details. The challenge I have is on adding data into the body of my POST request. The data I want to add there I am getting is from another page as PROPS.

I want to add it to the body, inside an object called bundle as an array.

for example:

bundle: {cart.attributes}.

When that is done I display the response on the page.

Below I have attached the code I am using.

import React, { useState } from "react";

function App({ cart }) {
  
  console.log(cart);
  const handleSubmit = () => {
    const token = "fb83b937-2739-3d6e-9519-09387b92dfae";
    const data = {
      transactionReference: "string",
      paymentMethod: "CreditCard",
      checkoutOrderUrl: "http://www.test.com/",
      user: {
        name: "string",
        msisdn: "+27610983142",
        email: "[email protected]",
      },
      payementMethodDetail: {
        RedirectUrl: "http://www.test.com",
        PurchaseEventWebhookUrl: "http://www.test.com",
      },
      bundle: [
        {
          productCode: "311",
          amount: 100,
          currencyCode: "ZAR",
          quantity: 1,
        },
      ],
    };
    const requestOptions = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(data),
    };
    fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/",
      requestOptions
    )
      .then((response) => response.json())
      .then((res) => console.log(res));
  };

  return (
    <div className="App">
      <button type="submit" onClick={handleSubmit}>
        Post items
      </button>
    </div>
  );
}

export default App;

This is what the cart data looks like

enter image description here

I used redux.. i dispatch data successfully. i try to get data other page. Its shows error like Uncaught TypeError: undefined (reading ‘category’)

my code .

import React from 'react'
import { useSelector } from 'react-redux';

export default function ProductDetail() {

    const product =  useSelector((state)=>state)
    const datas = product.allProducts.products.Data
    console.log('data',datas )
  return (
  )
}

this code executed correctly and gave correct output.. but i want const datas = product.allProducts.products.Data.category

when i try to get category data its shows error like Uncaught TypeError: Cannot read properties of undefined (reading ‘category’) .

my json data

"Data": {
        "banner": [
            {
                "BannerId": 1,
                "BannerImage": "image 10_1650873105.png",
                "BannerTitle": "product banner1",
                "BannerDescr": "The products with 50% offer1"
            }
        ],
        "category": [
            {
                "CatId": 23,
                "CatName": "laptop",
                "CatImage": "kari-shea-1SAnrIxw5OY-unsplash_1650877809.jpg"
            }
        ]
    }

Add styling to translation string in i18n-js React Native

I use i18n-js for translation purposes in my React Native app. But I cannot get any styling like different colors, bold etc. to my translations.

This is my en.js:

import {Text} from "react-native";

  const highlightText = (string) =>
    string.split(" ").map((word, i) => (
      <Text key={i}>
        <Text style={{ backgroundColor: "#ECEAFF", color: "#5F5C7E" }}>
          {word}
        </Text>
      </Text>
    ));

const en = {
   testTranslation:`This Text has some styling to it: ${highlightText("<h1>Hello</h1>")} isn't that pretty?`,

I use the translation on my screen like this:

import i18n from "i18n-js";
import { de } from "../../../locales/de";
import { en } from "../../../locales/en";
import { fr } from "../../../locales/fr";

i18n.fallbacks = true;
i18n.translations = { en, de, fr };

...
 <Text>
     {i18n.t("testTranslation")}
 </Text>

The outcome is this:

This Text has some styling to it: [object Object] isn’t that pretty?

Any help how to style the text is much appreciated!

How add data from API to favourite and save in localStorage

I would like to save the books fetched from the API to favourites and keep a list of favourite books in localStorage so that when the page is refreshed, the favourites list does not disappear.

The books are fetched from the API in the BooksView.js component. The API is constructed in such a way that only 10 books can be fetch and to fetch and display more books I have to send a request for another 10 from the next page in the API. I use the ChangePageButton to send a new request and download more books

In the BookView.js component the list of books fetched from API is saved to a new array of objects and for each book a new key is added with information if the book is in favorites or not. I map the newly created array and if the book has the favourite: true key I display a full heart icon ( <FavouriteBook>) and if it doesn’t have the favourite key I display an empty heart icon.

My problem is that I fetch a list of 10 books from the API and when I fetch a list of more books it overwrites the favorites list with the new list of books.

I don’t know how to solve this problem to save list of favorite books in separate variable which will be saved in localStorage and when opening page list of favorite books will be downloaded from localStorage and selected books will be marked as favorite.

BookView.js

import { styled as materialUIStyled } from "@mui/material/styles";
import Paper from "@mui/material/Paper";
import Button from "@mui/material/Button";
import Link from "@mui/material/Link";
import styled from "styled-components";

import { Grow } from "@mui/material";
import BookCover from "../images/default_book_cover.jpg";
import FavouriteBook from "../favourite-book";
import { useEffect, useState } from "react";

const Img = materialUIStyled("img")({
  margin: "0px",
  display: "block",
  maxWidth: "150px",
  maxHeight: "200px",
});
const MainStyles = styled.div`
  display: flex;
`;
const BooksContainer = styled(MainStyles)`
  //   height: 100vh;
  gap: 20px;
  flex-wrap: wrap;
  justify-content: center;
  margin: 0 50px;
`;

const BookContainer = styled(MainStyles)`
  gap: 5px;
  padding: 15px;
  flex-wrap: wrap;
  justify-content: center;
`;
const BookInfoContainer = styled(MainStyles)`
  gap: 30px;
  width: 100%;
  margin: 10px;
`;

const BookInfoParagraph = styled.span`
  font-size: 16px;
`;
const BookTitleName = styled.h2`
  margin: 2px;
  font-size: 20px;
  font-weight: bold;
`;
const ErrorContainer = styled(BooksContainer)`
  font-size: 50px;
  align-items: center;
  height: 100vh;
  text-align: center;
`;
const ButtonsContainer = styled(MainStyles)`
  gap: 20px;
`;

const BookView = ({ data, setData, error, errorMessage }) => {
  const [favorites, setFavorites] = useState([]);

  useEffect(() => {
    setFavorites(data);
  }, [data]);

  useEffect(() => {
    console.log(favorites);
    console.log(data);
  }, [favorites]);

  if (error) {
    return (
      <ErrorContainer>
        <p>
          Error
          <br></br>
          {errorMessage}
        </p>
      </ErrorContainer>
    );
  }

  function handleFavorite(id) {
    const newFavorites = favorites.map(item => {
      return item.id === id ? { ...item, favorite: !item.favorite } : item;
    });

    setFavorites(newFavorites);
  }
  return (
    <BooksContainer>
      {Array.isArray(data) &&
        data.map(
          book =>
            book.type === "Text" && (
              <Grow key={book.id} in timeout={500}>
                <Paper
                  sx={{
                    p: 2,
                    width: "450px",
                  }}>
                  <BookContainer>
                    <BookInfoContainer>
                      {book.resources.map(
                        item =>
                          item.type === "image/jpeg" &&
                          item.uri.includes("medium") && (
                            <Link
                              target="blank"
                              href={`https://www.gutenberg.org/ebooks/${book.id}`}>
                              <Img
                                key={item.id}
                                alt="book-cover"
                                src={item.uri}
                              />
                            </Link>
                          )
                      )}
                      {book.resources.length < 11 && (
                        <Img alt="book-cover" src={BookCover} />
                      )}
                      <div>
                        <BookInfoParagraph>Book title:</BookInfoParagraph>
                        <BookTitleName>{book.title}</BookTitleName>
                        <BookInfoParagraph>Author:</BookInfoParagraph>

                        {book.agents.map(
                          item =>
                            item.type === "Author" && (
                              <BookTitleName key={item.id}>
                                {item.person}
                              </BookTitleName>
                            )
                        )}
                      </div>
                    </BookInfoContainer>
                    <ButtonsContainer>
                      {book.resources.map(
                        item =>
                          item.type.includes("text/html") &&
                          item.uri.includes(".htm") && (
                            <Button key={item.id} variant="outlined">
                              <Link
                                underline="none"
                                target="blank"
                                href={item.uri}>
                                QUICK READ BOOK
                              </Link>
                            </Button>
                          )
                      )}
                      {favorites.map(
                        (item, i) =>
                          book.id === item.id && (
                            <FavouriteBook
                              key={item.id}
                              add={item.favorite}
                              handleClick={() => {
                                handleFavorite(item.id);
                              }}
                            />
                          )
                      )}
                    </ButtonsContainer>
                  </BookContainer>
                </Paper>
              </Grow>
            )
        )}
    </BooksContainer>
  );
};

export default BookView;

BooksView.js

import { useEffect, useState } from "react";
import axios from "axios";
import PageWrapper from "../../common/page-wrapper";
import ChangePageButton from "./change-page-button";
import BookView from "./book-view";
import ProgressCircle from "./progress-circle";
import styled from "styled-components";

const ChangePageButtonContainer = styled.div`
  position: fixed;
  top: 50%;
  left: ${props => props.theme.left};
  right: ${props => props.theme.right};
`;
const leftPosition = {
  left: "15px",
};
const rightPosition = {
  right: "15px",
};
const BooksView = () => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [forwardPageLoading, setForwardPageLoading] = useState(false);
  const [backPageLoading, setBackPageLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [error, setError] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  useEffect(() => {
    fetchData(page);
  }, [page]);

  const fetchData = page => {
    axios(`https://gnikdroy.pythonanywhere.com/api/book/?page=${page}`)
      .then(res => {
        setData(res.data.results);
        setIsLoading(false);
        setForwardPageLoading(false);
        setBackPageLoading(false);
      })
      .catch(err => {
        setError(true);
        setIsLoading(false);
        setErrorMessage(err.message);
        console.log("Error", err.message);
      });
  };

  let count = page;
  const handleForwardPage = () => {
    setForwardPageLoading(true);
    if (page === 6578) {
      setPage(1);
    } else {
      count += 1;
      setPage(count);
    }
  };
  const handleBackPage = () => {
    setBackPageLoading(true);
    if (count === 1) {
      setPage(6578);
    } else {
      count -= 1;
      setPage(count);
    }
  };
  // console.log("data", data);

  return (
    <>
      {isLoading ? (
        <ProgressCircle height="100vh" />
      ) : (
        <PageWrapper>
          <ChangePageButtonContainer
            theme={leftPosition}
            style={{ display: `${error ? "none" : "inherit"}` }}>
            {backPageLoading ? (
              <ProgressCircle />
            ) : (
              <ChangePageButton handleClick={handleBackPage} type="back" />
            )}
          </ChangePageButtonContainer>

          <section>
            <BookView
              setData={setData}
              data={data}
              error={error}
              errorMessage={errorMessage}
            />
          </section>
          <ChangePageButtonContainer
            style={{ display: `${error ? "none" : "inherit"}` }}
            theme={rightPosition}>
            {forwardPageLoading ? (
              <ProgressCircle />
            ) : (
              <ChangePageButton
                handleClick={handleForwardPage}
                type="forward"
              />
            )}
          </ChangePageButtonContainer>
        </PageWrapper>
      )}
    </>
  );
};

export default BooksView;

FavouriteBook.js

import { Button, Icon } from "@mui/material";

const FavouriteBook = ({ handleClick, add }) => {
  return (
    <Button onClick={handleClick}>
      <Icon sx={{ color: "red" }}>{add ? "favorite" : "favorite_border"}</Icon>
    </Button>
  );
};

export default FavouriteBook;