javascript – How can I route change when scroll up and down with reactjs?

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

reactjs – (PERN Stack) Question regarding the storage of data (with Apollo client/server)

I’m having some kind of a struggle.
I’m building an using the spacex api, i use the graphql endpoint to fetch my data: https://spacexdata.herokuapp.com/graphql

From there, the data is generated with graphql code generator and is strictly on the client side, it doesn’t interact with the server side where my user db is.

I have a user entity that looks like so:

import { Field, Int, ObjectType } from "type-graphql";
import { BaseEntity, Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";

@Entity()
@ObjectType()
export class User extends BaseEntity {

    @Field(() => Int)
    @PrimaryGeneratedColumn()
    id: number

    @Field()
    @Column({unique: true})
    username: string

    @Field()
    @Column({unique: true})
    email: string

    @Column()
    password: string

    @Field(() => String, {nullable: true})
    @Column({nullable: true})
    avatar?: string

    @Field(() => String, {nullable: true})
    @Column({nullable: true})
    first_name?: string

    @Field(() => String, {nullable: true})
    @Column({nullable: true})
    last_name?: string

    @Field(() => String)
    @CreateDateColumn()
    created_at: Date

    @Field(() => String)
    @UpdateDateColumn()
    updated_at: Date
}

I’d like, when the user is logged in (i got that part covered aswell), to be able to bookmarks flight from the spacex api and i’m not sure how to proceed.

My questions are the following:

  1. Should I store the flight in a separate entity and do relationship with the user entity ?
  2. Should I create a new variable of type (Flight) that point to a separate class (that isn’t necessary an entity, just a model class) ?
  3. Should I store the bookmarks flight in the client side ?

Thank you !

react.js – React functional components: Pattern for keeping parent aware of a value within a child

Although case one and case two shown below both work, I have these two questions (the first question is why I’m here… I’m happy to ask the second one on Stack Overflow, but it seems like the second one might be worth considering vis a vis the ideal pattern for the situation that comes up below):

Question #1

What are the considerations behind deciding between passing the out of the box setWhatever from useState() down to a child (see case one below) versus creating a custom handleWhatever function to pass to the child, where the handleWhatever function uses setWhatever within it (see case two below)?

Question #2

Both cases result in the warning shown below… which may or may not mean that the best practice pattern for having a child update a parent’s state is something other than one of my two cases… here is the warning:

Warning: Cannot update a component (Test) while rendering a different component (DetermineValue). To locate the bad setState() call inside DetermineValue, follow the stack trace

Definitely React is about passing state down from parent to child. But after reiterating that fact, it seems like we are always left with countless examples where a function is passed from parent to child for the purpose of keeping a parent aware of a certain value within the child. My question is about such cases where a function needs to be passed down to a child. (If someone is 100% sure that all such cases of passing a function to a child are misguided… then, of course, I’m open to learning about why!! I don’t claim to have absolute certainty that it is a sound pattern for functions to be passed to children for the purposes of updating a parent).

Case #1

// Test.js (parent, case one)
import React, { useState } from 'react';
import DetermineValue from './DetermineValue';
const Test = () => {
  const (importantValue, setImportantValue) = useState();
  console.log(importantValue);
  return <DetermineValue setImportantValue={setImportantValue} />;
};
export default Test;

// DetermineValue.js (child, case one)
import React from 'react';
const DetermineValue = ({ setImportantValue }) => {
  setImportantValue('Important Data');
  return <></>;
};
export default DetermineValue;

Case #2

// Test.js (parent, case two)
import React, { useState } from 'react';
import DetermineValue from './DetermineValue';
const Test = () => {
  const (importantValue, setImportantValue) = useState();
  const handleSetImportantValue = (importantValueQuickPass) => {
    setImportantValue(importantValueQuickPass);
  };
  console.log(importantValue);
  return <DetermineValue handleSetImportantValue={handleSetImportantValue} />;
};
export default Test;

// DetermineValue.js (child, case one)
import React from 'react';
const DetermineValue = ({ handleSetImportantValue }) => {
  handleSetImportantValue('Important Data');
  return <></>;
};
export default DetermineValue;

reactjs – React Hooks, API, Axios

I have a problem in my axios api calls, i’m using 2 apis in the same function, both of axios calls works good alone but when i combine them i got error in the Country components which i will be posting after, the error is ( map is not a function )

const onSerializeData = () => { 
    const serializedCountries = serializeCountries(selectedCountries, false);
    //Print the Countries
    console.log(
      `Selected Countries: n ${JSON.stringify(serializedCountries)}`
    );
    
    axios
      .get(
        `https://restcountries.eu/rest/v2/alpha/${
          serializedCountries(serializedCountries.length - 1)
        }`
      )
      .then((responose) => {
        const CouAllData = responose.data;
        console.log("CouAllData", CouAllData);
        setCountryAllData((...CountryAllData, CouAllData));
      })
      .catch((error) => {
        console.log("Error", error);
      });
      axios
      .get(
        `https://corona-api.com/countries/${
          serializedCountries(serializedCountries.length - 1)
        }`
      )
      .then((responose) => {
        const CouData = responose.data.data; //The Data
        setCountryData((...CountryData, CouData)); //set The Data to the OBJ
        console.log(" setCountryData", CountryData);
      })
      .catch((error) => {
        console.log("Error", error);
      });
  };
return (
<div>
<Country countries={CountryData} /> 
      <Country countriesAll={CountryAllData} /></div>
}

Country Component

const DataGroup = this.props.countries.map((county) => {
      return <Data info={county} />;
    });

    const DataGroupAll = this.props.countriesAll.map((country) => {
      return <Data infos={country} />;
    });

    return (
      <div>
         {DataGroup}
         {DataGroupAll}
      </div>

Data Component

 <h1>Name : {this.props.info.code}</h1>
        <h1>Date : {this.props.info.updated_at}</h1>
<h1>Name : {this.props.infos.name}</h1>
        <h1>Capital : {this.props.infos.capital}</h1>

reactjs – Pl upload zip the file before uploading

I am trying to zip the file before uploading with plupload

Plupload.bind('FilesAdded', (up, files) => {
   // 1. Check file
   // 2. Access file content here (Need input how we can access it? or pass file object to JS zip)
   // 3. Zip the file using // using JS Zip may be, this need blob, or array or content
   // 4. Add Zipped content in queue, with new file name and remove current file from the queue.
}

I am looking for help regarding point number 2 and 3. Where in I need to extract file content and pass blob or file object to JS Zip so it can zip it correctly.

Thanks for help.

reactjs – Next.js / React app architecture best practice

I’m building an app with Next.js aimed at teachers & students. The teachers will control the students screens, navigating them through a collection of steps and interactive activities. I’m using WebSockets to manage the communication between teacher and student clients.

I’m still pretty new to React and Next.js and my question is around the best way to structure the apps. Is it best to separate each step/activity? into its own page or would it be better to have a single page with a separate component for each step/activity?

Happy to hear any advice / best practices you can share!

How to use d3 with reactJS / nextJS?

I would like to add a d3 chart, following the tutorials but nothing happens at all. i’m actually not sure if useEffect() is at the good "timing", if I should use componentDidMount, or if it’s just not the good way to add in the element… Seems like I’m missing something here!

import React from 'react';
import * as d3 from "d3";
import { useEffect } from 'react';

function drawChart() {
  const data = (12, 5, 6, 6, 9, 10);
  const h = 100;
  const w = 100;
  const svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h)
    .style("margin-left", 100);
                  
    svg.selectAll("rect")
      .data(data)
      .enter()
      .append("rect")
      .attr("x", (d, i) => i * 70)
      .attr("y", (d, i) => h - 10 * d)
      .attr("width", 65)
      .attr("height", (d, i) => d * 10)
      .attr("fill", "green")
}


const chart: React.FunctionComponent = () => {
  useEffect(() => {
    drawChart();
  }, ());
  
  return (
    <div>
    </div>
  );
};
export default chart;

reactjs – “Gatsby build” orders jsx improperly, but gatsby develop doesn’t

An <a> tag with a <div> inside is generated with the entire <a> tag (including closing tag) before the <div> that is supposed to be inside it. When running “gatsby develop” this never happens and before today “gatsby build” didn’t have this issue either.

For reference:

<a href={props.link} target="_blank" rel="noreferrer" className={"tile is-child" + (isolated ? " is-3" : "")}>
            <div className="card m-3 is-clickable is-link">
                <div className="card-image">
                    <InfoOverlay name={props.status} color={props.statusColor ? props.statusColor : "light"} overlayLink={props.overlayLink} />
                    <figure className="image is-2by1">
                        <img src={props.image} alt={props.name + " Image"} style={{ objectFit: "cover" }} />
                    </figure>
                </div>
                <div className="card-content">
                    <div className="media">
                        <Icon props={props} />
                        <div className="media-content">
                            <div className={"title" + (props.tSize !== "undefined" ? " is-" + props.tSize : " is-3")} style={{ paddingTop: sizeDict(tSize)(0), paddingBottom: sizeDict(tSize)(1) }}>{props.name}</div>
                        </div>
                    </div>
                </div>
            </div>
</a>

I can’t seem to find this issue anywhere else, but that could be the case of me not knowing where to look (this is my first gatsby project and my first relatively complex react project). If this is too little information, let me know and I can send more. Any help would be appreciated!

reactjs – ElectronJS app with credential sharing external servers for cookie and session storage

I want to store a session cookie that a server sends but cors is blocking it,since the origin of the request is not a from a http://www.someaddress.com so I cant whitelist it, in the cors and axis I’m passing the parameter credentials:true. Some forus say to use origin:’*’ but then that gets denied

reactjs – How to get position of ionic element in React

I have question regarding scrolling in React with Ionic. So i have a header witch starts off large and as I scroll pass an y point i want to change some css. The IonContent have some events for scrolling but i dont seem to find a way to get the current y position of the ioncontent. Does anyone have a clue for how to work around this or if im just missing something that is very easy?

I tried to do it with js also by targeting classnames but that did not seem to work either and i dont really want to do it this way unless it is the last and only way.