How to preview a picture after upload with reactJs?

I’m using ReactJs for frontend. I have a file upload part everything is working good but I want to preview the picture after uploading and before submitting the form.
Anyone suggest for me how to implement a FileReader in my code ?

this is my code :

 const [unitList, setUnitList] = useState([]);
  const [errorList, setError] = useState([]);
  const [presentAdress, setPresentAdress] = useState("");
  const [permenantAdress, setPermenantAdress] = useState("");
  const [file, setFile] = useState("");
  const [unit, setUnit] = useState("");

  useEffect(() => {
    axios.get(`http://localhost:8000/api/listUnit`).then(res => {

      setUnitList(res.data);
    });
  }, [])

  const addOwner = (e) => {
    e.preventDefault();
    const formData = new FormData();
 
    formData.append('presentAdress', presentAdress);
    formData.append('permenantAdress', permenantAdress);
    formData.append('file', file);
    formData.append('unit', unit);
    axios.post(`http://localhost:8000/api/addOwner`, formData).then(res => {
      if (res.data.status == 200) {
        new Swal("Success", res.data.message, "success");
        setError([]);
        window.location.reload(false);

      }
      else if (res.data.status == 422) {
        new Swal("All Fields are mandetory", "", "error");
        setError(res.data.errors);
      }

    });


  }




this is the view of file :

<div className='d-flex'>
          <img className="owner-picture" style={{ width: 150, height: 150 }} src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoGBxEUERYTFBMUExERERMYGRYWExYWFhYaFhIbGxgWFhYaHysiGx8oHRYYJDQjKSwuMTExHCE3PDcvOyswMS4BCwsLDw4PHBERHTAoISgwMjAuMDIwMDAwMjAwMTAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMP/AABEIALwBDAMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAAAQYEBQcDAv/EAD0QAAIBAgEJBQUGBgIDAAAAAAABAgMRBAUGEiExQVFhgSJxkaGxBxMyQlIjgpLB0eEUYnKywvBTcyRDov/EABoBAQADAQEBAAAAAAAAAAAAAAADBAUCAQb/xAAxEQACAQIEAwYFBAMAAAAAAAAAAQIDEQQSITFBUWEFcaGx0fATMoGR8SMzUsEiQuH/2gAMAwEAAhE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GpCE1/NFPwvsK88Mn8pfp9ozWk1fwfv7HITPyDkmeIqqEdS2ylbVGO99+5Fhy3mS9JSw71Skk4Tl8N98ZPXZb09ffsLNkDI1PDU9COuT1ylvk/yS3Iihh5OVpbFirjoKneG78O/+upm4PCxpwjTgrRhFJLuMgAvGMAAAAAAAAAAAAAAAAAAAAADzlA9AAeAPRwPhoAgAAAkg8sZO1Ob4Rl6ajxuyuNys1JXbfFt+LNtm7PVOPBp+Kt+SNObLN+fba4x9Lfqz5zAStiIt8b+KZpV1+mzdgA+kM0AAABI+4wPtIA+Kd7a1Z77az0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPhwPhRfA9gAeLRhZZnajLnor/6X5JmyZ8VYJqzSa5q5xVg5wlFcU0dRdmmU8y8kTtWjzuvGL/OxYf4Sl/xw/BH9BTw8FrUYruSMun2ZOnJTzLRp7FmeKi01Y+gos9STXKh5qmfSij6AAAAAAAAAAAAAAAAAAAB/9k=' alt='Generic placeholder image' height='100' width='100' />
          <div className='d-flex align-items-end mt-75 ms-1'>
            <div>
              <Button tag={Label} className='mb-75 me-75' size='sm' color='primary'>
                Upload
                <Input type='file' onChange={(e) => setFile(e.target.files[0])}
                  hidden accept='image/*' />
              </Button>
              <p className='mb-0'>Allowed JPG, GIF or PNG. Max size of 800kB</p>
            </div>
          </div>

How to find a unique string within html and wrap it with a tag, but exclude links and urls

I’m looking for a way to look for a specific string within a page and then wrap that string in <em> tags. I have tried used HTML Agility Pack and had some success with a Regex.Replace but if the string is included within a url it also gets replaced, if it’s within an image name, it gets replaced and this obviously breaks the link or image url.

An example:

   var markup = Encoding.UTF8.GetString(buffer);
        var replaced = Regex.Replace(markup, "product-xs", " <em>product</em>-xs", RegexOptions.IgnoreCase);
        
        var output = Encoding.UTF8.GetBytes(replaced);
    
        _stream.Write(output, 0, output.Length);

This would replace a <a href="product/product-xs"> with <a href="product/<em>product</em>-xe">

The string is coming from a text string value within a CMS so the user can’t wrap the words there and ideally, I want to catch all instances of the word that are already published.

Ideally I would want to exclude <title> tags, <img> tags and <a href> and <a> tags, everything else should get the wrapped tag.

Before I used the HTML Agility Pack, a fellow front end dev tried it with javascript but that had an unexpected impact on dropdown menus.

If you need any more info, just ask.

How to avoid UI freezing with React

Consider this little react app:

import React, { Component } from "react";
import PropTypes from "prop-types";

import { Audio } from "react-loader-spinner";

import "./styles.css";

async function blockingUI() {
  let x = 0;
  for (let i = 0; i < 10000; i++) {
    for (let j = 0; j < 10000; j++) {
      x = Math.sqrt(x + i * j);
    }
  }
  return x;
}

async function setTimeoutAsync(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

class Foo extends Component {
  static propTypes = {
    classes: PropTypes.object,
    style: PropTypes.object,
  };

  static defaultProps = {};

  // -------- Public: Reactjs --------
  constructor(props) {
    super(props);
    this.state = {
      ...props,
      isLoading: false,
    };
  }

  setLoading = (isLoading) => {
    this.setState({
      isLoading: isLoading,
    });
  };

  setLoadingAsync(isLoading) {
    return new Promise((resolve) => {
      this.setState({
        isLoading: isLoading
      }, resolve)
    });
  }

  onBlockingUi = async () => {
    let widget = this;
    widget.setLoading(true);
    console.time("blockingUI");
    await blockingUI();
    console.timeEnd("blockingUI");
    widget.setLoading(false);
  };

  onBlockingUiHacked = async () => {
    let widget = this;
    widget.setLoading(true);
    await setTimeoutAsync(20);
    console.time("blockingUI");
    await blockingUI();
    console.timeEnd("blockingUI");
    widget.setLoading(false);
  };

  onNonBlockingUi = async () => {
    let widget = this;
    widget.setLoading(true);
    await setTimeoutAsync(1000);
    widget.setLoading(false);
  };

  render() {
    const loader = this.state.isLoading ? (
      <Audio heigth="100" width="100" color="grey" ariaLabel="loading" />
    ) : null;
    return (
      <div className="App">
        <h1>Loading test</h1>
        <h2>Click to see some magic happen!</h2>
        <button onClick={this.onBlockingUi}>Blocking UI</button>
        <br/>
        <button onClick={this.onBlockingUiHacked}>Blocking UI + hack</button>
        <br/>
        <button onClick={this.onNonBlockingUi}>Non-blocking UI</button>
        {loader}
      </div>
    );
  }
}

export default function App() {
  return <Foo />;
}

In the above example there are 3 buttons:

  1. When I press the one that says “Blocking UI” the spinner widget won’t show up and the UI will freeze up.
  2. When I press the one that says “Blocking UI + hack” the spinner widget will show up but it won’t update/re-render properly (UI frozen up)
  3. When I press the one that says “Non blocking UI”, everything works ok.

I’d like to know what’d be the best practice here so I can avoid blocking the UI when trying to run these type of CPU intensive functions such as blockingUI while displaying some loading html elements.

You can find the codesanbox here: https://codesandbox.io/s/sharp-roman-bouy9l

Execute a custom function when the rate limit is exceeded (rate-limit-mongo)

Package: npm install –save rate-limit-mongo

ROUTE:

routes.get(
    "/example",
    general,  // This is my rate limit
    (req, res) => {
    return res.status(201).end()
    }
)

MIDDLEWARE:

module.exports.general = new RateLimit({
store: new MongoStore({
    uri: process.env.MONGODB_CNN + "api-limiter",
    expireTimeMs: 15 * 60 * 1000,
    errorHandler: console.error.bind(null, 'rate-limit-mongo'),
    collectionName: "general",
}),
max: 50,
windowMs: 15 * 60 * 1000,
skipSuccessfulRequests: true
});

Thank you in advance

how can i make the form in html inside expanded table dosent close until sending the form?

I didnt know how to write this code in a way to make the form inside every row in a table not close until i click on send button ,because my background in javaScript is little .

Also i didnt konw how to make the icon appear in a table data inside the table

<section class="main">
    <div>
      <table>
         <tr>
           <th> Name </th>
           <th>Title</th>
           <th>Description</th>
           <th>Evaluate</th>
          </tr>
          <tr onClick='toggleRow(this)'>
             <td>Dr.sasa</td>
             <td>B System</td>
             <td>the project .....</td>
             <td><button><a><i class="fa-solid fa-arrow-down-long"></i></a></button></td>
          
          <div>
             <td class='expanded-row-content hide-row'> 
            <form action="">
              <div class="in-form">
                <p class="Evaluate-QForm"><span>eee</span> </div>  
                  
              <input type="radio" id="approve" name="Evaluate">
              <label for="approve">approve </label>
              <input type="radio" id="reject" name="Evaluate">
              <label for="reject">reject</label><br>

            
              <label for="comment">Comments </label>
              <input type="textarea" id="comment"name="comment" >


              <input type="submit" value="Send">
            </div>
          </div>
            </form>


          </td>
        </tr>

        <tr onClick='toggleRow(this)'>
          <td>Dr.Ree </td>
          <td>S System</td>
          <td>Application .....</td>
          <td class="ev-arrow-button"><a> <i class="fa-solid fa-arrow-down-long"></i></a></td>

          <td class='expanded-row-content hide-row'>
            <form action="">
              <div class="in-form">
              <p class="Evaluate-QForm"><span> eee</span> </div> 

              <input type="radio" id="approve" name="Evaluate">
              <label for="approve">approve </label>
              <input type="radio" id="reject" name="Evaluate">
              <label for="reject">reject</label><br>
              </p>

              <p class="Ev-Com-Qform">
              <label for="comment">Comments </label>
              <input type="textarea" id="comment"name="comment" >
              </p>

              <div >
              <input type="submit" value="Send">
              </div>
            

            </form>


          </td>
        </tr>

    </table>

    </div>


</section>

const toggleRow = (element) => {
element.getElementsByClassName(‘expanded-row-content’)[0].classList.toggle(‘hide-row’);
console.log(event);
}

Disabled Radio Button Based on Previous Selection

const lightOption_AA = document.getElementById(
    "ProductSelect-option-Light-Option-Amber-Dotted (Amber LED)"
);
const lightOption_SA = document.getElementById(
    "ProductSelect-option-Light-Option-Smoked-Dotted (Amber LED)"
);
const lightOption_SW = document.getElementById(
    "ProductSelect-option-Light-Option-Smoked-Dotted (White LED)"
);
const forwardLight_SB = document.getElementById(
    "ProductSelect-option-Forward-Light Function <span>(switchback only offered on strip lights)</span>-Switchback"
);
const forwardLight_SQSB = document.getElementById(
    "ProductSelect-option-Forward-Light Function <span>(switchback only offered on strip lights)</span>-Sequential-Switchback"
);

if (
    lightOption_AA.checked ||
    lightOption_SA.checked ||
    lightOption_SW.checked
) {
    forwardLight_SB.disabled = true;
    forwardLight_SB.style["color"] = "#aaa";
    forwardLight_SQSB.disabled = true;
    forwardLight_SQSB.style["color"] = "#aaa";
} else {
    forwardLight_SB.disabled = false;
    forwardLight_SQSB.disabled = false;
}

CodePen Link <– So I have three fieldset tags, each has a few inputs of type=radio inside.

Now, when a user selects any Light Option with the name or word “Dotted” (i.e. the first three options within the corresponding fieldset) I want to disable the Forward Light Function options that have the word or name “Switchback” in them (i.e. the two last options within the corresponding fieldset).

The logic is there, and I feel as if it is on the tip of my tongue. But for some reason, it doesn’t disable the radio buttons.

The id attributes are dynamically created by Shopify and not myself and that is why they are so long and descriptive and have spaces in them. But I did some console logging and the variables still get assigned regardless of this.

I am sure the answer is easy and I am going to feel stupid.

Any help would be appreciated. –> CodePen Link

React Scrolling using overflow

I am building a website with react and I am using a navigation bar. I implemented react-scroll and with Link I was able to scrollTo each css id element. But I also want to scroll (with fingers) through the website.

This is my NavigationBar:

const ContentBar = () => {
return(
    <div id="navbar" className="navbar-box">
        <div className={open ? "navbar active" : "navbar"}>
        <Bounce right cascade duration={800}>
                <ul className="navlink">
                    <li><Link to="about" activeClass="active" spy={true} smooth={true} duration={700}><img src={Logo} alt="logo"/></Link></li>
                    <li><Link to="skills" activeClass="active" spy={true} smooth={true} duration={700}>Home</Link></li>

        </Bounce>
        </div>
    </div>
)}

These are the css elements for the ids:

.skillspage {
  position: absolute;
  padding:50px 0 50px 0;
  margin-top: 80px;

}
.about {
  position: absolute;
  width: 100%;
  top: 15%;
  height: 50%;
  max-width: 100%;
  margin-top: 14%;
  align-self: center;
  align-content: center;
  align-items: center;

}

Both elements are childs in the following div:

.px {
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  max-width: 100%;
  display:flexbox;
  height: 100vh; 
  overflow: auto;
  

}

No here’s the problem: If I change the overflow property in .px to ‘hidden‘ I can only scroll with the NavigationBar, but if I change the overflow property to auto or scroll I can only scroll with my fingers.

How can I solve this problem?

React router: useParams() returns undefined even when destructured

I am using the useParams hook in react. I have a component where I want to load the ID from URL.

import React from 'react';
import { useParams } from 'react-router-dom'

const FakeGame = () => {

  let { thisId } = useParams();

  console.log(thisId);
  console.log(useParams());

  return (
    <h1>This ID is: {thisId}</h1>
  )
}

export default FakeGame

the useParams() console log shows the data I want in an object, but destructuring it returns undefined. I have the routes one level up in the App:

  <Link to="/">Home</Link>

  <Routes>
    <Route path="/:id" element={<FakeGame currentId={currentId}/>}></Route>
    <Route path="/" element={<Home currentId={currentId} setCurrentId={setCurrentId}/>} />
  </Routes>

And the Link to the FakeGame component in a Games component here:

  const Games = ({ setCurrentId }) => {
  const games = useSelector((state) => state.games);
  
  return (
    !games.length ? <CircularProgress /> : (
      <Grid className={mergeClasses.container} container alignItems="stretch" spacing={3}>
        {games.map((game) => (
          <Grid key={game._id} item xs={12} sm={6}>
            <Link to={`/${game._id}`}>FAKE GAME</Link>
            <Game game={game} setCurrentId={setCurrentId}/>
          </Grid>
        ))}
      </Grid>
    )
  )
}

Am I going about this correctly?

My file structure is

- App.js
+ components
  - FakeGame.js
  + Games
    - Games.js

Mongoose Schema show the array if a friendId exist in Users Model schema

I have created a user which has its login data and into it is has some arrays including friends, groups, pages and other stuff.
But I am stucked when I want see who has sent me a friend request.
So I have am trying to create the friend request/response as in Facebook.
My logic it is for the moment when I send you a friend request I add to my array of friends and then with post request I can see at which users is my ID added and it has the status Pending.
For the moment I have tried something but I am getting empty array as response.
My code is below.

user.service.js backend

const User = require("../models/user");
async function findYourPendingContact({friendId}) {
    return await User.find({friends: friendId});
}

module.exports = {
    findYourPendingContact
}

routes.js

routes.post("/user-friends", UserController.findYourContacts);

This is the Controller.

const userService = require("../service/user.service");
async findYourContacts(req, res, next) {
    let friendId = req.body.friendId;
    userService.findYourPendingContact({friendId: friendId})
    .then(friends => res.json(friends))
    .catch(err => next(err));
}

So seems my Database Json.
The user that added me as friend.

{
    "_id" : ObjectId("620bfd2d860fd314fc538df3"),
    "firstName" : "Max",
    "email" : "[email protected]",
    "lastName" : "Muster",
    "password" : "$2b$10$D8l15CTZHbp/rcApqXpwT.KUbHAg0hBYp0h1qounnKFW.plDO9wKe",
    "phone" : {
        "number" : "1234566",
        "countryCode" : "DE",
        "dialCode" : "+49",
        "e164Number" : "+491234566",
        "internationalNumber" : "+49 1234566",
        "nationalNumber" : "1234566"
    },
    "gender" : 1,
    "birthday_day" : "13",
    "birthday_month" : "8",
    "birthday_year" : "1998",
    "friends" : [
        {
            "friendId" : "6204605617d5fcc3c179f3cc", // this here is my ID
            "status" : 0,
            "createdDate" : {
                "$date" : 1644971031461
            }
        }
    ],
    "__v" : 0
}

Here are my Data on backend

{
    "_id" : ObjectId("6204605617d5fcc3c179f3cc"),
    "firstName" : "Test",
    "email" : "[email protected]",
    "lastName" : "Test",
    "password" : "$2b$10$koGb0fIcdWvq2ugGQXF7.OOmoof1QCH8IKQtoMGl9MHSJuu5Xumd6",
    "phone" : {
        "number" : "01234567",
        "countryCode" : "DE",
        "dialCode" : "+49",
        "e164Number" : "+4901234567",
        "internationalNumber" : "+49 01234567",
        "nationalNumber" : "01234567"
    },
    "gender" : 0,
    "birthday_day" : "8",
    "birthday_month" : "5",
    "birthday_year" : "1994",
    "__v" : 0
}

Now this is the part of my frontend when I login.

 public getUserFriends(userId): Observable<any> {
    const api = `${this.baseUrl}/user-friends`
    return this.http.post(api, JSON.stringify({friendId: userId}), this.httpOptions).pipe(
      map((response: User) => {
        console.log(response);
        return response;
      },
      (err) => {
        throw err;
      })
    )
  }

user.helper.ts

  showPendingFriends(authId): Observable<any> {
    return new Observable<any>(observer => {
      this.userService.getUserFriends({friendId: authId}).subscribe(response => {
        observer.next(response);
      })
    })
  }

components.ts

 this.userHelper.showPendingFriends(this.authService.userID).subscribe(res => console.log(res));

mapping keys of Object in javascript

I would like to change key names in such object:

const data = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4',
}

with those keys from map:

const map = {
'key1': 'change1',
'key4': 'change4'
}

Using code below:

const replacedKeysInData = Object.keys(data).map((key) => {
const keyFromMap = map[key] || key;
return { [keyFromMap]: data[key] }
})
console.log(replacedKeysInData);

I get:

[
{ change1: 'value1' },
{ key2: 'value2' },
{ key3: 'value3' },
{ change4: 'value4' }
]

The point is that I would like to have it in one object:

{ 
change1: 'value1',
key2: 'value2',
key3: 'value3',
change4: 'value4' 
}

I suppose it is simple, how can I do it?
Thanks

Using JavaScript to Check Multiple Checkboxes

I have a form, within it is a table with multiple checkboxes and text input boxes. The checkboxes do not have ids, only different attributes. I want to check off multiple boxes when I run the script in the console. I cannot edit the HTML. This is what I’ve got so far, but I’m not sure how to get it to work, or if it is even possible. Thanks for any help.

function chk () {
  document.querySelector('[name="A"]').checked = true; 
  }
<form>
<table>
    <TR>
         <TD align="left"><INPUT TYPE=CHECKBOX NAME="A">A:</TD>
         <TD align="right"><input type="text" name="effDateTxtA" value="" class="detailstyle"></TD>
    </TR>
 </table>
 </form>

How to do API endpoint testing in Express JS using JEST?

There is an app with a several Express JS endpoints that are dependent on a MongoDB database ( Atlas to be more specific )

I’ve been struggling to figure out how to write appropriate integration tests with Jest testing framework.

First steps I want to accomplish:

  • To have an local testing database connection when the tests are run.
  • To start the application in test environment and wait for the database to successfully connect first before running the tests.

Current situation:

  1. App is being required from a module ( this executes the code and the app starts as like in normal development environment ).
  2. Tests takes place.
  3. Test results being outputted to the console.
  4. Information about whether database connection is succeeded or not follows up.

I assume that as per standard asynchronous behavior of NodeJS the tests are in some sort of racing condition with the database connection.

Would be awesome if someone could give me a hand understanding this environment switching from development to testing or any references to articles or any sort of information would be appreciated.

const request = require('supertest')
const app = require('../dist/app')

describe('Authentication API testing', () => {
    it('SHOULD RETURN Content-Type: application/json HEADER WITH Content-Length: 54 AND HTTP STATUS CODE 400 WHEN DOING POST /auth/register WITHOUT EMAIL ', () => {
        return request(app)
            .post('/auth/register')
            .send({ password: 'testPassword' })
            .expect('Content-Type', /json/)
            .expect('Content-Length', '54')
            .expect(400)
    })
})