When props data to child component my items is not displayed ? React

When I props the data on child component do not appear propertly data to me.

First check my parent compnent:

  selectFile = (event) => { // on select file and upload
    let addedFiles = []; 
    event.target.files.forEach((element) => {
      addedFiles.push(element);
    });  
    this.setState({
      tempFiles: addedFiles,
      modalTempFiles: this.state.old.concat(addedFiles),
      old: this.state.old.concat(addedFiles)
    }); 
  };


  componentDidMount() { 
    //  I NEED TO USE SETTIMEOUT BECAUSE MY PROPS DATA IS NULL ON MOUNT
    setTimeout(() => { 
      this.setState({
        tempFiles: this.props.files.exFiles,
        modalTempFiles: this.props.files.exFiles,
        old: this.props.files.exFiles
      });
    }, 1500);
  }

HTML: (check only FileUploadContainer component )

  render() {
    const {
      intl,
      onHideAttachmentsModal,
      files,
      show,
      onHideErrorModal,
      showErrorModal
    } = this.props;
    const { modalTempFiles } = this.state;
    return (
      <>
        <Modal
          show={show} 
          title={intl.formatMessage(messages.attachments)} 
          primaryButtonTitle="Upload attachment(s)"
        > 
           //RIGHT NOW JUST THIS COMPONENT IS IMPORTANT -> FileUploadContainer
          <FileUploadContainer
            stopPropagation={this.stopPropagation}
            onFileDrop={this.onFileDrop}
            selectFile={this.selectFile}
            files={this.props.files?.exFiles}
          />

          {modalTempFiles.length > 0 && (
            <FileContainer
              files={modalTempFiles}
              onClickHandler={this.removeFile}
            />
          )}
        </Modal> 

      </>
    );
  }

My state is :

this.state = {
  tempFiles: [],
  modalTempFiles: [],
  old: []
};

Now I’m props some data in my children’s component. To my FileUploadContainer component.

This is my child component:

const FilesContainer = ({ intl, files, onClickHandler, fullWidth }) => {
  console.log("files", files);
  return (   
        {files.map((file, index) => (
          <File
            key={index}
            name={file.name}
            size={file.size}
            onClickHandler={() => onClickHandler(file, index, true)}
          />
        ))} 
  );
};

Don’t show me names and sizes… I see three items printed in loop but name and size is empty…

One of the interesting things is that my console.log (‘files’, files) is printed more than 4-5 times..

What’s the problem here? Why I am shown 3 items (as many as I need) but with empty values.
What I example see:

  1. Name : EMPTY , Size: EMPTY,
  2. Name : EMPTY , Size: EMPTY,
  3. Name : EMPTY , Size: EMPTY

BUT THREE TIMES LOOPED AS IT SHOULD BE because i have three items…

Having problems making a post request using the Ckeditor

How do I push the data from my text editor into the formData object, in the content section? inside the CkEditor tag I need to be able to make name={content} and value={content} similar to how they are set in the input tags

import { useState } from 'react';
import { CKEditor } from '@ckeditor/ckeditor5-react'
import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
import { createPost } from '../../services/Posts.js'
import { useHistory } from 'react-router';


function CreatePosts(props) {
  const { currentUser } = props;
  const history = useHistory()
 const [formData, setFormData] = useState({
    image: '',
    category: '',
    title: '',
    subtitle: '',
    content: '',
  });
  const { image, category, title, subtitle, content } = formData;
  const [body, setBody] = useState('')

  const handleChange = (e, editor) => {
    const { value, name } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  return (
    <div>
      <img class="explore-image" src="https://res.cloudinary.com/tylerwashington98/image/upload/v1638051076/Meta-Minds/decentraland_naqec7.jpg" alt="banner image"></img>
      <div class="latest-and-all-posts-main-divs">
        <form class="create-post-form"
          onSubmit={(e) => {
            e.preventDefault();
            createPost(formData);
            history.push(`/user-posts/${currentUser?.id}`)
          }}
        >  <h1 class="create-post-header-text">Create Post</h1>
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Image URL</div>
            <input
              class="create-post-user-input-box"
              type='text'
              name={'image'}
              value={image}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Category</div>
            <input
              class="create-post-user-input-box"
              type='text'
              value={category}
              name={'category'}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Title</div>
            <input
              class="create-post-user-input-box"
              type='text'
              value={title}
              name={'title'}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Subtitle</div>
            <input
              class="create-post-user-input-box"
              type='text'
              value={subtitle}
              name={'subtitle'}
              onChange={handleChange} />
          </label>
          <br />
          <label class="create-post-label-and-input-div">
            <div class="create-post-input-text">Content</div>
            <div className="edits">
              <CKEditor
                editor={ClassicEditor}
                onChange={(event, editor) => {
                  const data = editor.getData()
                  setBody(data)
                }}
              />
            </div>
          </label>
          <button>Submit</button>
        </form>
      </div>
    </div >
  );
}

export default CreatePosts

How do I push the data from my text editor into the formData object, in the content section? inside the CkEditor tag I need to be able to make name={content} and value={content} similar to how they are set in the input tags

How to store values such as name and mobile when create user with email and password Firebase? React Native

can somebody explain and give example on how to store extra data when crate user with firebase9? I can only create user with email and password. But how to add data such as name, image, etc? There is a function add data? but this is in firebase database which is separate from authentication. It gets different document id, and thus, I can not linked it to a specific user?
Please some clarification how to save additional data when creating a user with firebase 9 and where and how to read that data?

Slider issue – html css

thank you for looking into my issue.

I am creating a small website: http://testgod0312.000webhostapp.com/
I have an issue with my slider.

#1 I cant position the p below the image. There is a problem with the height currently absolute from top of section. More importantly, I struggle to align the p in the middle of the screen

#2 There is a weird item at the end of each p and i dont know how to remove it…

#3 I struggle to position the arrows, I would like them on the border of the image, not border of the screen

my p and img are absolute positions, because I have to overlap them. Then with a js script, an image becomes active and the other non_active

The html is:

 <div class="slider">
    <h2><span class="red">The Hierarchy</span></h2>
    <img src="assets/img/Slider/img1.jpg" alt="img1" class="img__slider active" />
    <img src="assets/img/Slider/img2.jpg" alt="img2" class="img__slider" />
    <img src="assets/img/Slider/img3.jpg" alt="img3" class="img__slider" />
    <p class="p__slider active"> test 1 blqblqbqbl blqblqbqbl blqblqbqbl blqblqbqbl </p>
    <p class="p__slider"> test 2</p>
    <p class="p__slider"> test sdaa</p>
    <div class="suivant">
        <i class="fas fa-chevron-circle-right"></i>
    </div>
    <div class="precedent">
        <i class="fas fa-chevron-circle-left"></i>
    </div>
</div>

The CSS is here (also slider.css in the asset folder on site):

.slider {
    height: 62vh;
    position: relative;
    margin: auto;
    background: var(--color1);
    justify-content: center;
    text-align: center;
}

.slider h2 {
    margin-bottom: 1rem;
    font-size: 2rem;
    text-align: center;
}

.slider img {
    object-fit: cover;
    max-width: 1200px;
    height: 50vh;
    width: 90%;
    position: absolute;
    opacity: 0;
    transition: opacity .5s;
    transform: translateX(-50%);
}

.slider img.active {
    opacity: 1;
}

.slider p {
    margin: auto;
    font-size: 1.5rem;
    position: absolute;
    top: 57vh;
    opacity: 0;
    transition: opacity .5s;
    color: var(--color2);
    max-width: 1200px;
    width: 1200px;
}

.slider p.active {
    opacity: 1;
}

.suivant, .precedent {
    color: #fff;
    font-size: 2.5rem;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
}

.suivant {
    right: 1rem;
}

.precedent {
    left: 1rem;
}

To note, suivant refers to the next arrow and precedent to the previous arrow

Thank you for your help guys!!

React rendering resources properly only on initial load. After that some resources dont render

Ive been having a strange problem for the past few days and I cant find a fix.
Im making a react app. Note – im using a css/bootstrap theme. And only some resources (mainly images but sometimes whole css blocks) render properly only on the initial start of the app. After that when I navigate to a different page, stuff doesnt load properly. And then when I get back to the home page – stuff is not loading properly that has loaded properly beforehand.
Ive checked the network tab and it seems im getting all the resources on the initial load. Its just strange that they dont render properly later when the router gets used.
If I want it to render properly I can only do it by refreshing the page. And then its the same again.
Im really struggling to find a fix to this, ive searched many different options but they all dont apply to my case.
Im sorry if my explanation wasnt very clear, im not that good with english.

Getting an error ‘Unknown column’ in ‘order clause’ using typeorm

I’m trying to create a query with typeorm and MySQL.
I keep getting the following error:

[Nest] 44806 – 12/09/2021, 2:37:03 PM ERROR [ExceptionsHandler]
ER_BAD_FIELD_ERROR: Unknown column ‘sort_order’ in ‘order clause’
QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column ‘sort_order’ in
‘order clause’

My query is:

const { limit, page: skip, userLat, userLng, searchQuery, weekday, startHour, endHour } = options;
let stores;

// get only stores that open in the start and end hours range
const openHoursQuery = `
      '${startHour}' BETWEEN `from` AND `to` AND
      '${endHour}' BETWEEN `from` AND `to`
      AND weekday = ${weekday}
  `;

// get the distance from user's location to each store
const getDistanceQuery = `
      SQRT(
        POW(69.1 * (lat - ${userLat}), 2) +
        POW(69.1 * (${userLng} - `long`) * COS(lat / 57.3), 2)
      ) AS distance
    `;

stores = this.storeRepository.createQueryBuilder('store')
  .leftJoinAndSelect('store.hours', 'store_hours')
  .addSelect(userLat && userLng ? getDistanceQuery : '')
  .where(searchQuery ? `name LIKE '%${searchQuery}%'` : '')
  .andWhere(weekday && startHour && endHour ? openHoursQuery : '')
  .orderBy(userLat && userLng ? 'distance' : 'sort_order')//sort_order
  .take(limit)
  .skip(skip)
  .getManyAndCount();

return stores;

The problem is caused by the “leftJoinAndSelect” method, when I comment the join the query executes without any problems.

My DB tables look like this:

TABLE: stores

COLUMNS: id, uuid, name, status, address, URL, email, lat, long, sort_order

Table: store_hours

COLUMNS: id, store_id, weekday, from, to, type

Upload to firebase error “.storage.ref is not a function”

Inside my index.js file:

export function postArticleAPI(payload) {
   return(dispatch) => {
      const upload = storage
        .ref(`images/${payload.image.name}`)
        .put(payload.image);
      upload.on("state_changed", (snapshot) => {
        const progress = (
          (snapshot.BytesTransferred / snapshot.totalBytes) * 100);
          console.log(`Progress: ${progress}%`);
        if(snapshot.state === "RUNNING") {
          console.log(`Progress: ${progress}%`);
        }
      },
      (error) => console.log(error.code),
      async() => {
        const downloadURL = await upload.snapshot.ref.getDownloadURL();
        db.collection("articles").add({
        ...
        });
      });
    }
  };
}

I look in the docs provided by firebase but I am unsure how to implement that. When I run the code above, I get “TypeError: firebase__WEBPACK_IMPORTED_MODULE_0_.storage.ref is not a function” error.

I messed around with the code and I’ve also gotten other errors such as: “…storage.put is not a function,” I’ve gotten errors with upload, as well as db.collection error.

Here’s my firebase.js:

import { initializeApp } from 'firebase/app';
import { getAuth, GoogleAuthProvider } from 'firebase/auth';
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
...
}

const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth();
const provider = new GoogleAuthProvider();
const storage = getStorage(firebaseApp);
  
export { auth, provider, storage };
export default db;

Any help would be appreciated (and this is my first post, so please let me know if I need to add anything else). Thanks!

After clicking on the button, the input new value returns to the old value

I need advice, I’m doing such an extension JS, but maybe I’m making a mistake in that the app runs on Angular

var input1 = document.getElementsByClassName("vypln")[0];

var enter = new CustomEvent('keyup');
enter.which = 13;
enter.keyCode = 13

input1.focus();input1.value="";
document.execCommand('insertText', false, 4);
input1.dispatchEvent(enter);

document.getElementsByClassName('buttons')[0].querySelector('button').click();

The data is written to the input, … but after clicking on the button, the old value is set. I want value to stay there and do it.
Interestingly, if I use this code and then click (mouse / manually) anywhere and then call document.getElementsByClassName('buttons')[0].querySelector('button').click(); so it works fine.
Thank you all for the advice)

how to pop up datalist options for input tag in html

I’m currently trying to add to my datalist for my input text field in html. The way I do it is to retrieve text from backend and dynamically generate options in datalist, however, after I retrieve all texts at my frontend and generate option to datalist, there is only one option display instead all.

Here is the way I add option to my datalist:

async function getSuggestedWords(event) {
    let datalist = document.getElementById("suggestions");
    let text = document.getElementById("q").value;
    let http = new XMLHttpRequest();
    http.responseType = "json";
    // let str = "";
    http.onload = async function() {
        if (this.readyState == 4) {
            let  {suggestions}   = http.response;

            for (let suggest of suggestions) {
                console.log(suggest.term);
                let s = document.createElement('option');
                s.setAttribute("value", suggest.term);
                datalist.appendChild(s);
            }
        }
    }

    const url = `http://localhost:8080/api/suggest?q=${text}`;
    await http.open("GET", url);
    await http.send();
}

here is my html:

        <label for="q">Input</label>
        <input type="text" name="q" id="q" list="suggestions" onchange="getSuggestedWords(event)" autocomplete="on">
        <datalist id="suggestions">
        </datalist>

Nextjs passing ids to through link

I’ve created a component named ArticleList this component’s purpose is to display a list of articles that are returning from an API. When clicking on the article title it will redirect to that individual page which I’ll then fetch data for. The API used needs an article id parameter which I have access on the ArticleList component. I am having issues passing this id to the [...blog] page I created.

How can I redirect to this dynamic blog page without passing the ID in the URL? If I’d like to show the id in the URL then I would not have any issues as I can access it from next.js router but because I do not want it in the URL I am having issues with coming up with an alternative working way.

I’ve attempted to do some research if possible, to hide the query strings in the URL when on the page but based on my research that does not look like it is possible in next.js. Also based on my research there is no next/Link property I can use to pass this without displaying it in the URL.
The code snippet I am having issues with is:

 <Link href={`/blog/${ConvertCodeTitleToURL(d.name)}`}>
      <a className="text-body-black font-weight-500 letter-spacing-15 text-20 m-b-8">
          {article.title}
         </a>
   </Link>

Here is an example of the ArticleList component:

import Image from "next/image";
import Link from "next/link";

function ConvertCodeTitleToURL(title) {
  let url = "";

  if (title) {
    url = title.replace(".", "").toLowerCase();
    url = url.replace(/,/g, "");
    url = url.replace("(", ""); // added for (except) cases
    url = url.replace(/s/g, "-");
  } else {
    url = "/";
  }

  return url;
}

const ArticleList = ({ categories, articles }) => {
  let combinbedarr = categories.results.map((item, i) =>
    Object.assign({}, item, articles[i])
  );

  return (
    <div className="container-1200">
      {combinbedarr &&
        combinbedarr.map((d) => (
          <>
            {d.results.length > 0 && (
              <div key={d.id}>
                <div className="d-flex justify-space-between">
                  <div className="heading-30 letter-spacing-25 text-dark-blue m-l-n-20">
                    {d.name}
                  </div>
                  <Link
                    href={`/categories/${ConvertCodeTitleToURL(d.name)}/?id=${
                      d.id
                    }`}
                  >
                    <a className="text-16 font-weight-500 letter-spacing-25 text-blue m-r-120">
                      All {d.name} <i className="fas fa-arrow-right"></i>{" "}
                    </a>
                  </Link>
                </div>
                <div className="d-flex align-center m-b-32 flex-wrap">
                  {d.results &&
                    d.results.map((article) => (
                      <>
                        <div className="m-r-32 card-resources">
                          <div
                            key={article.id}
                            className="m-b-20 ct-relative card-resources-img m-b-20"
                          >
                            <img
                              className="div-100"
                              alt=""
                              layout="responsive"
                              height="180"
                              src={`test.api.com/${article.seoImageUrl}`}
                            />
                          </div>

                          <div className="article-content">
                            <Link
                              href={`/blog/${ConvertCodeTitleToURL(d.name)}`}
                            >
                              <a className="text-body-black font-weight-500 letter-spacing-15 text-20 m-b-8">
                                {article.title}
                              </a>
                            </Link>
                            <div className="m-b-20">
                              {article.seoDescription}
                            </div>
                            <div className="d-flex m-b-20">
                              {article.tags &&
                                article.tags.map((tag) => (
                                  <div className="ct-topics" key={tag}>
                                    {tag}
                                  </div>
                                ))}
                            </div>
                          </div>
                        </div>
                      </>
                    ))}
                </div>
              </div>
            )}
          </>
        ))}
    </div>
  );
};
export default ArticleList;

[...blog] page that I would like to have access to the id

const blog = () => { 
    // logic to fetch article data using the ID from `ArticleList`
return (
<div></div>

    )
}
  

export default blog 

Sending a function with a parameter through an .onclick listener

I’m a beginner web developer who is in the process of putting together a simple website that will use an API to display data from various cities based on different buttons a user can click. I’ve written a general function that takes in a city parameter, runs it through the api and sends the appropriate data back to my HTML page. I’m just having trouble getting the event listener for my buttons to work as expected.

Listener examples:

city1button.onclick = cityInfo("city1");
city2button.onclick = cityInfo("city2");

Based on some research, I now realize that my code is invoking my functions before a button can be pressed. I’ve found some more elaborate solutions online, but was wondering if there is a simple way that could ideally be kept in one line. Thanks in advance. I really appreciate the help.

A-Star pathfinder for a Canvas sprite using javascript?

I am trying to make a 2d game using javascript Canvas, but I need the sprites to be able to navigate around the map using AStar (or something similar). I’ve tried researching a bit into this, but I can’t manage to understand how to do what I want. I need the pathfinding function to return the path as a list of consecutive coordinates to go towards in order to get to the target tile.
Would someone be able to make a function (or point me in the direction of one) that would do something like this:

var map =
  [
    [0, 0, 1, 0, 1],
    [1, 0, 1, 0, 0],
    [0, 0, 0, 1, 0],
    [0, 1, 0, 0, 1],
    [0, 0, 1, 1, 1],
    [1, 0, 0, 0, 1]
  ]
var currentPos = [0, 0];
var targetPos = [5, 3];

function pathFind(map, start, end) {
 // Coding Stuff......
}

listOfMovesToMake = pathFind(map, currentPos, targetPos);
// returns array of coordinates
// i.e. [ [0, 1], [1, 1], [2, 1], [2, 0], [3, 0], [4, 0], [4, 1], [5, 1], [5, 2] ]

I like the concept of pathfinding, but the math and brain power required is painful.
Thanks to anybody that can help.

group array of object by property value

I have this array of objects:

[
 {
   day: 1,
   status: red,
   count: 3
 },
 {
   day: 1, 
   status: blue,
   count: 5
 },
 {
   day: 2,
   status: red,
   count: 10
 },
 {
   day: 2,
   status: blue,
   count: 1
 }
]

I want to re-factor this array into a new array and group by the day value:

[
 {
   day: 1,
   statusSummary: [
     {
       status: red,
       count: 3
     },
     {
       status: blue,
       count: 5
     }
   ]
 },
 {
   day: 2,
   statusSummary: [
     {
       status: red,
       count: 10
     },
     {
       status: blue,
       count: 1
     }
   ]
 }
]

what is the most efficient way to do this?

Visibility of arrays in javascript (“undefined”)

I tried to calculate the sum of two matrizes (multi-dimensional-arrays), but I get the following error-message:

Uncaught TypeError: Cannot set properties of undefined (setting '0')
    at matAdd (matrixCalc.js:28)

when I do this code↓. I don’t understand why “matSum[0][0]” is undefined.

// M1 + M2
function matAdd(m1, m2){        
    let matSum = new Array(m1.length);
    for (let i=0; i<m1.length; i++){       //create a blanco-matrix
        matSum=new Array(m1[0].length);
    }
    
    if (m1.length == m2.length && m1[0].length==m2[0].length){
        for (let i=0; i<m1.length; i++){
            for (let j=0; j<m1[0].length; j++){
                matSum[i][j]=m1[i][j]+m2[i][j];                  //HERE THE ERROR OCCURS
            }
        }
    }
    else console.log("Dimension-Error")
    return matSum;
} 

the code with line-numbers

Thx for the help 🙂

Counting word in message how to save

Here’s my code and my question is how can i change it to save numbers of counting?

After restart script it always back to 0

I don’t want change manually var test = 0;

const tmi = require('tmi.js'),
    { channel, username, password } = require('./settings.json');

const options = {
    options: { debug: true },
    connection: {
        reconnect: true,
        secure: true
    },
    identity : {
        username,
        password
    },
    channels: [
                '#qwerty',
    ]
};

var test = 0;

const client = new tmi.Client(options);
client.connect().catch(console.error);

client.on('connected', () => {
    client.say(channel, `Here`);
});

client.on('message', (channel, user, message, self) => {
    if(self) return;

        if(user.username == 'zzz' && message.includes('SSS')) {
            test++;
        }
        if(message == ('test')) {
            client.say(channel, 'xxx ' + test.toLocaleString());
        }
    });