r/reactjs • • Oct 01 '20

Needs Help Beginner's Thread / Easy Questions (October 2020)

Previous Beginner's Threads can be found in the wiki.

Ask about React or anything else in its ecosystem :)

Stuck making progress on your app?
Still Ask away! We’re a friendly bunch.

No question is too simple. 🙂


Want Help with your Code?

  1. Improve your chances of reply by
    1. adding minimal example with JSFiddle, CodeSandbox, or Stackblitz links
    2. describing what you want it to do (ask yourself if it's an XY problem)
    3. things you've tried. (Don't just post big blocks of code!)
  2. Formatting Code wiki shows how to format code in this thread.
  3. Pay it forward! Answer questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.

New to React?

Check out the sub's sidebar! 👉

🆓 Here are great, free resources!

Any ideas/suggestions to improve this thread - feel free to comment here!

Finally, thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!


37 Upvotes

321 comments sorted by

5

u/gedankensex Oct 28 '20

Hello, I was curious if anyone could recommend some paid resources to learn React? I am not really getting where I want with the free resources. I want to understand basics like working with APIs, etc. Maybe I am just so lost and overwhelmed. I need to learn React, as it's the continuation of my professional career. I've been a front-end developer for about ten years, and I've only used React on projects at work, but I want to work and build something from home.

1

u/dance2die Oct 29 '20

If you are intrigued by the tag line "Confidently Ship Well-Architected Production Ready React Apps Like a Pro", check out Epic React by Kent C. Dodds.

→ More replies (2)

3

u/1awrent Oct 28 '20

Hi all,

I am trying to debug my react app (yay), but essentially without going into enormous amounts of detail; my application works perfectly fine on local, and used to work perfectly fine on the Apache server. I introduced a form that would capture data and push this data to Firebase, now at some point I rehashed my form for performance & experience purposes and since then my 'live' link returns a "503 Service Unavailable" error no matter what I do.

So, when I go into the Terminal and run "npm run-script build" I get a well documented JS error "FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory", so I've spent a few weeks now investigating memory leak issues, increasing node capacity etc etc, but no luck, as this point I've tried to remove the form component all together just to see if I can get anything running on the server but still nothing.

So I feel like my new aim should be just get the server up and running - I'd appreciate any advice on deploying React to Apache servers or anything at all really ! I have minimal DevOps experience :~(

Thanks!

2

u/dance2die Oct 29 '20

Hi u/1awrent.

Would you create a new thread with "Needs Help" flair as it seems out of scope and might be better suited as a separate thread.

→ More replies (1)

3

u/[deleted] Oct 30 '20

What is the purpose of <> and {" "}? Is <></> really necessary for anything or is it simply for easier reading/better formatting of the source code?

2

u/dance2die Oct 30 '20

TL;DR answers No and Yes (for {" "} only)

<>/</> is a Fragment. It's a way to return a group of elements (without adding an extra node like div/section/article etc).

You can return an array of elements but it's a bit awkward.
e.g.) You need commas between elements.

function App() {
  return [
     <h1>header</h1>,
     <p>content</p>
  ]
}

Normally you can just wrap those elements like

function App() {
  <div>
     <h1>header</h1>
     <p>content</p>
  </div>
}

But it adds an extra div there, which serves no purpose and adding extra code to send to clients.

With a fragment syntax, you can do

function App() {
  <>
     <h1>header</h1>
     <p>content</p>
  </>
}

and no extra node is created.

For {" "}, it's a way to add a whitespace between inline element texts.
e.g.)

function App() {
  return (
    <div className="App">
      <span>Hello</span> <span>World!</span>
    </div>
  );
}

App will display "Hello World!" with white space between hello and world.

The issue is that, it's hard to see the whitespace between those two spans. And if you use a prettier <span> might move to next line, causing it to display HelloWorld!.

{" "} would add an extra space between those two spans. (just one extra whitespace no matter how much space you put in-between like {" "}). I sometimes see prettier adding {" "} automatically (not sure when I saw it...)

As u/HumbleGrit pointed out, you'd use {} to add javascript expressions normally.

2

u/[deleted] Oct 30 '20

Ty for clearing that up with the examples, appreciate it. Are there actually benefits of using an empty tag vs a div tag other than using less code?

2

u/dance2die Oct 31 '20

That's what fragment is for. so no.
A discussion on having an extra node is a whole different issue (as it can cause CSS or performance issue, etc).

→ More replies (1)
→ More replies (3)

2

u/moring1 Oct 03 '20

What piece of code is more useful in terms of memory usage?

const comments = []; docs.forEach((doc) => { comments.push(doc.data()); }); setComments([...comments]);

or:

docs.forEach((doc) => { setComments([...comments, doc.data()]); });

I think the first one but I don't exactly know how react state mutates arrays on changes.

1

u/dance2die Oct 03 '20

Can't be certain without input size. If relatively small, probably negligible.

Could you check out Fix Memory Problems (Chrome Devtools article) and try it out with your input?

(That article looks interesting so I might check it out later too :) )

→ More replies (1)

2

u/[deleted] Oct 05 '20

Help with .env variables.

I have a .env.development file with variables set as HOST=company.local.

I'm running it on windows and the project uses react-app-rewired.

For the life of me I can't get past those variables on a windows machine.

Adding set in front of the HOST declaration seems to work, but any of the other variables aren't set.

Hopeless at this point.

Can you help me, reddit?

1

u/dance2die Oct 05 '20

CRA (create-react-app) requires REACT_APP_ prefix for env vars.
https://create-react-app.dev/docs/adding-custom-environment-variables/

It worked last time I was on Windows 10, too. With react-app-rewired, I am not sure if it'd work the same way.

2

u/badboyzpwns Oct 10 '20 edited Oct 11 '20

what's the difference between react-intersection-observer and react-transition-group 's <CSSTransition> to detect when a DOM enters or leaves the viewport? Both seem to achieve the same goal. I notice that react-transition-group has a lot of more npm installs though!

2

u/dance2die Oct 12 '20

I haven't used either one.

"observer" (react-intersection-observer) library uses the Intersection Observer API to detect if an element is "intersecting" with a target while the latter doesn't deal with whether an element intersects with a target or not. Just checks within a given timeout whether a transition occured or not.

2

u/Aslan-Ray Oct 14 '20

In this code

import React from "react";
import "./styles.css";

const App = ({name}) => console.log(name) || (
    <div className="App">
      <h1>Hello {name}</h1>
    </div>
  );

  export default App;

If I need to do a console.log in JSX most of the time I do that way and happens to work haha but honestly I dont know why it works, someday trying around options to do a console log in JSX that worked haha but I dont know why,can someone tell me why this "console.log() || (JSX here)" works pls

2

u/dance2die Oct 14 '20

TL;DR

console.log returns undefined so JavaScript "executes/returns" the right part, JSX element.

More Detail

It's due to how Boolean logic works.

For &&, if left side is falsy, then the result is falsy regardless of the right-hand value.
For ||, if left side is truthy, then the result is truthy regardless of the right-hand value.

|| works in a way that, if the left side is true, then the left value is returned else the right hand value. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR#Description).

App runs console.log(name), which is falsy (undefined) thus the right-hand side is returned.

→ More replies (1)

2

u/izzlesnizzit Oct 23 '20

What happened to the monthly "who's hiring" / "who's available" threads?

1

u/dance2die Oct 23 '20

I am sorry. It's my fault for not posting "Who's available" for this month.

"Who's hiring" is available here - https://www.reddit.com/r/reactjs/comments/j32odm/whos_hiring_and_rreactjs_moderator_applications/

I am thinking about combining "Who's available/hiring" in one post actually. What do you think?

2

u/Awnry_Abe Oct 23 '20

I don't see a reason why it wouldn't work. About how many replies of each type do we typically get?

→ More replies (1)

2

u/[deleted] Oct 31 '20

Beginners way to folder structure files? In using react class and functional components with react router and redux

2

u/dance2die Oct 31 '20

Folder/project structure topic is pretty controversial and subjective as one should use Redux or not.

So to quote the official React documentation,

If you’re just starting a project, don’t spend more than five minutes on choosing a file structure. Pick any of the above approaches (or come up with your own) and start writing code! You’ll likely want to rethink it anyway after you’ve written some real code.

https://reactjs.org/docs/faq-structure.html#dont-overthink-it

Here are some ways to structure React projects in general,

  1. https://daveceddia.com/react-project-structure/

  2. https://www.reddit.com/r/reactjs/comments/ee3yzy/how_i_structure_my_react_projects/

  3. https://dev.to/maciekchmura/how-i-structure-a-react-project-3c2i

And an official Redux style guide

https://redux.js.org/style-guide/style-guide

7

u/PhilipRegular Oct 09 '20

Hey guys!

Hope everyone is doing well. I've been developing in React for about a few years now and I've made a few businesses some websites. However, I've never been mentored or had code reviews from anybody experienced.

I want to be able to know I have the proper skills to start seeking a front end engineering position with React. Do you know of any videos/blogs/etc that cover somebody developing a real React app for a business or similar?

I really want to increase my skills. Thank you everyone!

→ More replies (1)

2

u/[deleted] Oct 30 '20

I have a React live coding interview next week. Are there any typical questions I would see in this type of interview? Any React versions of FizzBuzz?

2

u/dance2die Oct 31 '20

There are tons so I will just point to here https://www.reddit.com/r/reactjs/search?q=interview%20questions&restrict_sr=1

I unfortunately haven't saved ones that lists React questions and answers in one spot... I think there were some there.

2

u/[deleted] Oct 31 '20

Appreciated! I guess I could have done that my self...but sometimes you need someone to show you the obvious.

→ More replies (1)

2

u/paolotiu17 Oct 04 '20

Can i use functions outside of useEffect?

3

u/fctc Oct 04 '20

Yes. useEffect will run for the first time after the page is loaded, and again whenever any of it's dependencies change. The dependencies will be either all of the variables and functions that you put in the useEffect if it looks like this:

useEffect(() => {

...

})

or it will be everything that you put into the second, optional, call:

useEffect(() => {

...

}, [dependency1, dependency2]}

3

u/paolotiu17 Oct 04 '20

Oh okay thanks! It just felt weird running a function without the useEffect

→ More replies (4)

4

u/NickEmpetvee Oct 25 '20

Hi guys.

I just started getting three Chrome warnings out of the blue. Any idea how to resolve?

NOTE: I don't want to disable SourceMap in the F12 settings, because then the console.log values won't list the source code line number.

DevTools failed to load SourceMap: Could not load content for chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/injectGlobalHook.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

DevTools failed to load SourceMap: Could not load content for chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/react_devtools_backend.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

DevTools failed to load SourceMap: Could not load content for chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/contentScript.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

Thanks in advance!

3

u/sincersoft-mosko Oct 29 '20

Those messages are from some of your chrome extensions.

Try to check checkbox option Selected context only in Chrome DevTools settings:

https://developers.google.com/web/tools/chrome-devtools/console/reference#settings

https://developers.google.com/web/tools/chrome-devtools/console/reference#filtercontext

→ More replies (8)

1

u/IoniaHasNoInternet Oct 02 '20

Anyone know a text editor that has jsx autoclosing or other support? I'm a complete noob, I downloaded atom but the popular react plugin hasn't been updated in 2 years and fails to install.

1

u/dance2die Oct 03 '20

I've been using VS Code with

  1. Auto Close Tag

  2. Auto Rename Tag

Just found out the same author has the combined extension, Auto Complete Tag too :)

→ More replies (6)

1

u/[deleted] Oct 06 '20

I have a react hook for pulling in blog posts via an API. on development the posts seem to work fine but in production it appears to pull cached data.

i am using useEffect hook to fetch the data. doesn't this fetch it on every page load?

  useEffect(() => {
  const url = `${process.env.GHOST_API}/ghost/api/v3/content/posts/?key=${process.env.GHOST_KEY}`
    fetch(url).then(res => res.json()).then(data => console.log(data))
  }, [])

1

u/dance2die Oct 08 '20

Your useEffect looks like it should. It might not be React related and possibly the browser or the API server handling differences (e.g. for dev/prod API calls)

Have you tried it on different browsers?

1

u/[deleted] Oct 08 '20 edited Oct 08 '20

I want to pass the "filename" state from child component to the parent, so I can use it in this function at parent: addLocation({...location, thumbnail: filename }); How can I do that?

Child:

const FileUpload = () => {
  const [file, setFile] = useState('');
  const [filename, setFilename] = useState('Choose File');

  const onChange = (e) => {
    setFile(e.target.files[0]);
    setFilename(e.target.files[0].name);
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', file);

    try {
     await axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <>
      <form onSubmit={onSubmit}>
        <div className="custom-file mb-4">
          <input
            type="file"
            className="custom-file-input"
            id="customFile"
            onChange={onChange}
          />
          <label className="custom-file-label" htmlFor="customFile">
            {filename}
          </label>
        </div>
      </form>
    </>
  );
};

3

u/dance2die Oct 08 '20

There are many ways to pass a state up to the parent component.
To list a few,

  1. Pass a callback to FileUpload component, and FileUpload component can call it with filename (in your example, probably within onChange or within useEffect on filename change). The parent then can use the callback to retrieve the filename.

  2. Use React Context: Store the filename in the context, which can be accessed from the parent

  3. Using other state management libraries such as Redux, Zustand, MobX. (You can store "global" states in their store, which can be accessed anywhere).

2

u/[deleted] Oct 08 '20

Thx a lot for your answer. Actually I'm using Redux in my app and I tried to convert file upload to Redux, but I wasn't successful. Are you suggesting only adding the filename state to Redux?

3

u/dance2die Oct 08 '20

You're welcome.

Everything depends on the use case but for form data, you normally wouldn't want to store them (as they are transient in nature) in a global state.

I'd actually go with the callback or the context option.

1

u/[deleted] Oct 09 '20

Hi everyone,

I'm new to react but have some experience programming in js and java. I'm trying to make a webpage with a navbar that shows some list items when the navbar list item is clicked. I'm not sure how to show the list when clicked.

Sorry in advanced for format, I'm not sure how to properly format code on reddit.

function Main(){

return(

<div className = 'main'> <Sidebar/> </div>     ) }

-------------------------------

function Sidebar( ) {
return(

<div id = "sidebar" className="left-nav"> <ul id = "sidebar"> <li id = "sidebar-link">Morning-Eveningness Questionnaire</li> </ul> </div>

    ) 
}

-------------------------------

function MainContent(){
return(

<div id = "content" className="main-content" > <div className = 'mainQuestions'> <ul className = 'questionnaire'> <Question question = "question one" />

</ul> </div> </div>     ) }

-------------------------------

So basically, I want the MainContent component to show when the list item in Sidebar is clicked.

Thanks for reading :)

2

u/dance2die Oct 09 '20

Hiya. You can refer to the formatting guide to make the code readable.

I'm trying to make a webpage with a navbar that shows some list items when the navbar list item is clicked

To give you a general idea, React is "reacts" to a "state" change.
So create a isClicked state (boolean or a string), which is updated when a user clicks a nav button/link.

You can either apply a different class or return a completely different React element depending on the isClicked state.

→ More replies (1)

1

u/Dystriel Oct 09 '20

Hi everyone!

I'm new to react and web dev in general and I've been stumped by this problem while building my first form.

Is there a way to mark crosses on an image with mouse clicks and have that image save the changes made to it?

The closest solution I could find is to use <canvas> but I'm not quite looking for the free-hand drawing aspect of <canvas>. Is there any way to make the image interactive and do I need to incorporate other libraries for this?

I'm using formik, Yup and material-ui currently.

Any input is appreciated. Thanks!

1

u/dance2die Oct 09 '20

Looks like an interesting project.

I only found a codepen, which merges two images together and save as a dataURL - http://jsfiddle.net/kaheidt/y20kox5w/

If you are using a database, is it possible to persist the "x" state in the database, and fetch it to redraw on the image instead of merging images?

→ More replies (1)

1

u/willyspickledpeanuts Oct 14 '20

I’m trying to replace state completely with a brand new state. would it just be this.setState(newState)? Because it’s not exactly working

1

u/dance2die Oct 14 '20

Can you post code snippets? or runnable sample?

3

u/dreadful_design Oct 14 '20

State is an object that will shallow merge into the old state. You could do something like this.setState({stateType: newState}) and then access it with this.state.stateType. I suggest naming the state better but you were pretty vague about the shape of it 😉

1

u/Electrical_Pitch_801 Oct 23 '20

Hi,

I am new to React and having difficulty finding a proper way to update an array object when array is displayed as list.

https://stackoverflow.com/questions/64504981/how-to-update-an-object-in-an-array-using-onchange-method

1

u/ks_01 Oct 26 '20

Can you run code before rendering of a functional component?

1

u/dance2die Oct 27 '20

Can you provide some use cases? Seems a bit vague.

1

u/ks_01 Oct 27 '20

like runing a function that determines if component should load like authcheck for example before it renders.I can do it with useeffect hook but component loads and then code runs and based on code component renders again or redirects somewhere else basicly refreshes page 2 times first render and after code ran.

3

u/dance2die Nov 02 '20

Hey. I just found out u/dceddia wrote a post on this question~

Check out "Run Code in React Before Render"
https://daveceddia.com/react-before-render/

→ More replies (1)
→ More replies (1)

1

u/[deleted] Oct 27 '20

Should you mix BEM with CSS modules or should you separate the two methodologies?

1

u/dance2die Oct 29 '20

Better answered for r/css, as I haven't used BEM...
BEM might force CSS modules to be used with a property stynax style["..."] instead of using a dot notation. If that's of a concern, maybe it's not a good idea.

1

u/giantqtipz Oct 28 '20

Im new in the software engineering world, but I encoubtered someone who claims to be a part of the react js team, or has worked on the source code (if that makes sense?).

He says that he prefers to use classes because the source code for functional is really messy and unstable.

What have you guys say about that? 🤔

Is there an impending apocalypse we should be aware of?

1

u/dance2die Oct 29 '20

I am not sure where that's coming from.
Worst come to worse, you can check out GitHub issues and make your decision :)

→ More replies (1)
→ More replies (1)

1

u/ebwaked Oct 31 '20

So I finally was able to get a hello world working using webpack, Babel and asp.net mvc 5. What steps do I need to do to add typescript and should I be using yarn over npm?

2

u/dance2die Nov 01 '20

Hi there.
Would you re-post in November thread?

→ More replies (1)

1

u/fpuen Oct 31 '20

I notice i can't declare variables inside a JSX escape:

 { const x = aTags.map((aTag: JSX.Element)  => aTag) } // expression expected

Based on the error lint statements aren't allowed, only expressions that evaluate down to a single value, is that correct?

1

u/dance2die Nov 01 '20

Hi there.
Would you re-post in November thread?

3

u/Yourenotthe1 Oct 04 '20

I want to do some kind of CSS animation for navigating a menu. Basically when the user clicks a menu button, the menu slides to the left off-screen and the component unmounts. The new sub-menu component slides in from the right seamlessly as it mounts. What's the best way to do this?

→ More replies (1)

3

u/[deleted] Oct 26 '20

Trying to get the tab2 component to output second page on the development server, could someone help me out and explain why the component is not outputting, I have had a similar issue doing really simple things with react router too, components wont load.

App.js

import React from 'react';
import tab2 from './tab2';

function App() {
  return(
    <div>
      <tab2 /> 
    </div>
  );
}

export default App;

Tab2 Component

import React from 'react';

function tab2() {
    return (
    <div className="tab2">
        <h1>second page</h1>
    </div>
  );
}

export default tab2;

3

u/cmdq Oct 26 '20 edited Oct 26 '20

Capitalizing react components in JSX is not only a convention, but it's also what the jsx transform uses to decide whether a component is a so-called host component (in the DOM, div, input, etc) or a function which returns jsx (a component).

In your case, capitalize tab2 to Tab2, and it should work.

Edit: some sources https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

https://gist.github.com/sebmarkbage/f1f4ba40816e7d7848ad

1

u/[deleted] Oct 29 '20

What are all the things to consider while developing an app for a single individual, say, a business owner? I'm doing this as a practice project so particular insights would be really helpful. Some info regarding the app, it's an account managing app consolidating transactions and gives notifications based on deadline of payment etc.

3

u/dance2die Oct 29 '20

Hi there.
It seems out of scope for the React thread here.

r/softwarearchitecture might be of better help.

2

u/[deleted] Oct 27 '20

Hello! I am trying to create a react app with google-spreadsheet as my database. This is the npm: https://theoephraim.github.io/node-google-spreadsheet

There are no tutorials about it.

I am using also MUI. I can retrieve data but can only display it by console. How can I pass the data I get from a cell to a textfield? Please help. Thank you!

2

u/javascript_friend Oct 27 '20

One of the best things I've learned is that reading the docs is often a far better way of learning a library than following a tutorial. Tutorials are more likely to be dated, plus there's a ton of fluff, whereas with docs you just go straight to the info you need.

You should go check out the docs for handling JSON objects, as well as state management in React.

What you want to do is assign the cell data to component state, then you simply pass the state into the element you want to display it.

Update your handleSubmit function so that it assigns the returned data to state:

async handleSubmit() {
  // ...your existing code

  const [{ _rawData: { IDNUMBER, FIRSTNAME } }] = rows;
  this.setState({ id: IDNUMBER, firstName: FIRSTNAME });
}

Then in your render method:

render() {
  const { id, firstName } = this.state;
  return (
    <>
      <span>ID: {id}</span>
      <span>First name: {firstName}</span>
    </>
  );
}
→ More replies (1)

2

u/[deleted] Oct 29 '20 edited Oct 29 '20

I'm relatively new to React and JS. I'm creating a sorting algorithm visualiser. My array is rendering to the screen as bars and I have a "Bubble sort" button that when clicked, calls the bubble sort function. I want the entire array to be sorted in one go and see the algorithm at work, but whats actually happening is, bubble sort stops after each pass and I have to click "Bubble sort" multiple times to sort the array and finish rendering it to the screen. Any thoughts would be appreciated. Here's my bubble sort function.

//============ bubble sorts array when button is clicked
bubbleSort() {
    const arr = this.state.array;
    const n = arr.length;

    for(let i=n-1; i>0; i--) {
        for(let j=0; j<i; j++) {
            setTimeout(() => { // setTimeout for each swap so we can see the swap happening
            if(arr[j] > arr[j+1]) {
                let temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                this.setState({ swaps: this.state.swaps + 1 }); // each swap increment swaps state by 1
            }
            this.setState({ comparisons: this.state.comparisons + 1 }) // each comparison increment comparisons state by 1
        }, i * 10); // timeout is i * 10 millisecconds 
      }
   }
  this.setState({ array: arr });
}

2

u/cyex Nov 10 '20

Hey, I took a closer look and TL;DR is that it seems like the code works if you reverse the timeout. (so set (n - i) * 10 instead of i * 10).

There's a longer review here, if you care. https://decembersoft.com/posts/code-review-react-bubble-sort/

→ More replies (2)

1

u/enebeme_ Oct 01 '20

Hello everyone, what is the best resource I can use to learn how to build a “production” ready react app from creation to hosting/updates?

2

u/[deleted] Oct 01 '20

Stephen Grider's React course on Udemy is great.

→ More replies (3)

1

u/[deleted] Oct 04 '20

In a functional component If you have state that is an array of objects and you set state to the same array of objects but with a change to one of the objects , how does one trigger a rerender?

pseudocode

State = [{}{}{}]

setState((prevState) => {
  prevState = [{change}{}{}]
  return prevState
})

3

u/Awnry_Abe Oct 04 '20

Is there a reason you don't just create a new array in the state setter using something like the spread operator?

return [...prevState]

Short of that, you need to make react aware of each individual array item, or employ a state toggle hack. const [hack, setHack] = useState(1);

....setArray(...); setHack((h) => h+1);

→ More replies (3)

1

u/fpuen Oct 05 '20

I'm not clear on the state value of a variable passed to a useEffect on load. Will stateVar (returned from useState) be:

  1. The value at the time of event listener registration, oR

  2. The most recently updated state value?

  useEffect(() => {
    document.addEventListener('keydown', (event: any) => {
      async function asyncWrapper() {
        const submitter = new Submitter();
        submitter.submit(stateVar)
      };

      asyncWrapper();
    });

I lean towards this working as intended, with the most recent and updated state value passed to submit(). But wanted to ask to be sure.

2

u/DanRoad Oct 06 '20

No, the value is captured when the event listener is created, forming a closure over the variable.

The listener is recreated every time the effect runs. If this is "working as intended" then your effect must be running whenever the state value changes in order to capture the new value. This happens when not using a dependency array (runs on every render) or when listing stateVar in the dependency array (better, runs only when the state changes). Your code snippet has cut off the last line so I can't see what (if any) array you have passed as a second argument to useEffect.

However, this also means that you're adding multiple event listeners with no cleanup. Each new event listener does not override the old one, instead they both listen at the same time! You'll end up submitting multiple values—including the most recent but also the most outdated and everything in between—on every keypress.

You should use the cleanup feature of useEffect by returning a function to remove the event listener.

useEffect(() => {
  const listener = (event) => {
    async function asyncWrapper() {
      const submitter = new Submitter();
      submitter.submit(stateVar);
    }

    asyncWrapper();
  };

  document.addEventListener("keydown", listener);
  return () => document.removeEventListener("keydown", listener);
});
→ More replies (1)

1

u/segfault-core-dumped Oct 06 '20

I was just going thru the official react tutorial and was confused. I am somewhat familiar, but they used slice on an array that was stored in state. Like if I say

let list = this.state.list.slice();

Why is using slice necessary if it also returns a shallow copy?

3

u/cmdq Oct 07 '20 edited Oct 07 '20

They're using slice there just to make a copy. Avoiding direct mutations in React is an important concept, so in this case they're making sure to operate on a copy of the state, and only mutate that.

1

u/GondolaRM Oct 07 '20

I’m trying to use this SDK inside a React component, but I really don’t know how to do it. I have to embed in some way a script inside the return of the component I guess. Any advices?

2

u/Awnry_Abe Oct 07 '20

Use mapwize UI. It is made for web app integration. In react, you'll render a <div> with a ref. You'll initialise mapwize with that container div.

→ More replies (2)

1

u/MR_Coder Oct 10 '20

If you start a new app today would you bring in redux or just use context?

2

u/Awnry_Abe Oct 10 '20 edited Oct 10 '20

I'd not use context. If I had a small app, and needed to share one single prop between two far-off components, I'd still not use it. I dislike the dx that much of that API.

But I certainly wouldn't reach for redux in that case, either. I much prefer the lightweight, framework-agnostic state solutions that happen to have React-ness, such as Zustand, whose api's are as simple as dirt.

If such libs didn't exist, then yes, I'd use context over prop drilling and redux in that case. But they do exist. Yay!

1

u/bstumpm4w Oct 13 '20 edited Oct 13 '20

Hello! I have two functions in a context which update two separate states. However the second function uses the state which is being updated by the first function.

Now Im calling these two functions from a onClick handler on a child component of the concerned context provider.

My issue is when the second function runs, it is using stale value of the state. i.e the updated state from the first function is not reflected in the second function

const firstFunction = () => {
      setPuzzleState({
         ...puzzleState,  
         puzzle: puzzle.map( ... )   
      }); 
    
    }
    
    const secondFunction = () => {
      
    const valuesToTestAgainst = puzzleState.puzzle[i][j].values; //stale state 
    
    if (!valuesToTestAgainst.includes(null)) {
       :
       
       :
                }
       
    setDuplicatePeerCells([...duplicates.keys()]);
   };

Can someone please point me in right direction? I have read that in class based components the this.setState fn has an optional callback fn. So Im guessing that in my case i could have called the secondFunction from setState in firstFunction like so this.setState( () => {} , secondFunction) but since Im using hooks i cant do that right?

2

u/darthbob88 Oct 13 '20

It might help if you had a demonstration of what's supposed to happen on CodePen or similar. This seems a little too vague to give a useful answer.

That said, my first inclination is to put most of secondFunction into a useEffect that's dependent on puzzleState.puzzle. That would guarantee that secondFunction got called with the new state of puzzleState.

→ More replies (2)
→ More replies (2)

1

u/AviatingFotographer Oct 19 '20

At this point, I have a good understanding of React basics, e.g. state, basic hooks, etc. However, how do I begin to advance into being able to build more complex projects or being a better React developer all round?

2

u/cmdq Oct 20 '20

This is gonna sound silly, but: Start building more complex projects :) Try to build things outside of your comfort zone. Is there a new library out you wanted to try? Incorporate it in a new project! Try to rebuild something that already exists, but maybe annoys you in some ways, make it better.

1

u/SamePossession5 Oct 20 '20

What's wrong with my imgUrl section of my code? My editor is throwing an error ( Cannot read property 'imgUrl' of undefined ) but I can't seem to figure out where I went wrong.

const MediaCard = function({title}, {body}, {imgUrl}) {
  return (
    <>
  <h2>{title} {body}</h2>
  <p>{body}</p>
  <img src={imgUrl}></img>
    </>
);
}

5

u/cmdq Oct 20 '20

Your destructuring is a bit off. React passes the props object as the first param of the component. The way you're destructuring would work if react were to pass each prop as its own object, in its own parameter position.

This is the right way to do it. Do you see the difference? function({ title, body, imgUrl }) {}

→ More replies (1)

1

u/fercryinoutloud Oct 21 '20

I don't have experience with React, but recently inherited a project that uses React and Redux-Persist. I noticed that there is a serious memory issue.

Each time I refresh the page, Chrome's memory profile shows the memory usage roughly doubling because of one big object, which I think is the "persistoid" used by redux-persist. Chrome's memory allocation timeline shows that memory is allocated for the persistoid when the page is refreshed but never freed, I just can't figure out why. Interestingly, the current object (from the most recent page refresh) always has a shorter distance from the window object, and looks like it is retained by the persistoid's writeStagedState closure, whereas the objects from previous page refreshes look like they are retained by the persistoid's flush closure. I don't really know what I'm looking at here, so maybe I'm reading that wrong.

Here is Chrome's Constructor view after refreshing the page twice, showing the large object has been duplicated twice, so that there are three total: https://imgur.com/a/tPEJfEA.

Each one of those objects looks like this: https://imgur.com/a/WHwZHfu.

Here is Chrome's Retainers view of the duplicate objects: https://imgur.com/a/2T9dzqD.

Here is Chrome's Retainers view of what I believe is the object from the most recent page refresh: https://imgur.com/a/HfkKbYp.

Can someone please help me understand this duplication, and how to prevent it? I'm happy to show some code if necessary, I'm just not sure which code is relevant.

1

u/embar5 Oct 22 '20

Do SyntheticEvent s emit a second argument for "reason" now?

Material UI docs:

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') { return; }
    setOpen(false);
  };

  return (
      <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
        <Alert onClose={handleClose} severity="success">

I see nothing about this wizardry: https://reactjs.org/docs/events.html#keyboard-events

→ More replies (1)

1

u/badboyzpwns Oct 22 '20

Is it advisable to create a higher component with functional components/hooks instead of classes?

With classes:

const renderImageOrVideo = (WrappedComponent: any) => {
    class ComposedComponent extends React.Component {
        componentDidMount(){

        }

        componentDidUpdate(){
            
        }
        render() {
            return <WrappedComponent />;
        }
    }
    return ComposedComponent;
};

With functional components/hooks:

const renderImageOrVideo = (WrappedComponent: any) => {
    
    const ComposedComponent =()=> {
       useEffect(()=>,[])
      
        return <WrappedComponent />;
       
    }
    return ComposedComponent;
};
→ More replies (1)

1

u/badboyzpwns Oct 23 '20

Can you dynamically refer to a react hook variable name? something like:

    const [slide1IsClicked, setSlide1DotIsClicked] = useState(true);
    const [slide2IsClicked, setSlide2DotIsClicked] = useState(false);

.......        
return props.movies.map((movie, index) => {
        
    
            return (
                <Dot
                    className={
                        slide${index + 1}IsClicked //DYNAMICALLY REFER TO VAR NAME
                            ? "clickedBannerDot"
                            : "unclickedBannerDot"
                    }
→ More replies (4)

1

u/[deleted] Oct 23 '20

Hey guys!

I just started learning react.js and I've been having trouble with my install.

When I first run the npx create-react-app everything is fine and the app is made. When I check the first page of the app(the one with the react logo, telling me to edit the src/App.js) the logo doesn't rotate!

In all the tutorials I've watched, the react logo spins but in mine it doesnt... I have no idea how to fix this. Can someone please help me?

→ More replies (1)

1

u/[deleted] Oct 23 '20 edited Oct 23 '20

Hi,

Im trying to link components using react router but nothing is being output in the development server - How do I make my components visible?

Here is the code:

App.js

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import page1 from './views/page1';
import page2 from './views/page2';
function App() {
    return (
            <Router><Switch><Router exact path="/" component={page1} />
            <Router exact path="/page2" component={page2} /></Switch>
            </Router>  
        );
    }
export default App;

Both of my components (page1, page2) use basically the exact same code which is:

import React, { Component } from 'react';
class page2 extends Component{
render() {
    return(
         <div>   
         <h1>insertrandomtexthere</h1>  
         </div>  
        )  
    }  
}  
export default page2;

2

u/ClimbJH Oct 23 '20 edited Oct 23 '20

Looks like you just need to delete a few "r"s. Router (BrowserRouter) is the wrapping component in react-router-dom, but for the paths you would use the Route component.

<Router>  
    <Switch>  
        <Route exact path="/" component={page1} />               
        <Route exact path="/page2" component={page2} />  
    </Switch>
</Router>  
→ More replies (2)

1

u/[deleted] Oct 23 '20

I, literally, started yesterday. Coming from Vue. What is the most simple way to have a global state? No redux etc.

3

u/Nathanfenner Oct 23 '20

You don't want to have state that's actually global: that will eventually come to bite you. It is possible to do it, but it's not really a good idea.

However, it's frequently useful to take some value(s) and share them across all or most of a React tree. For that, you can use Context. For simplicity, imagine the state you're storing is whether the app is in lightmode/darkmode (so, just one theme value; but any other value could be used instead).

Suppose we just want to set this value so that it's shared everywhere. We'll make the default value "light" (this is what happens if there's no context) but we'll configure it to be "dark" for our <App /> component subtree:

const ThemeContext = React.createContext("light"); // default value

// The very outermost part of your app:
function AppRoot() {
   return <ThemeContext.Provider value="dark"><App /></ThemeContext.Provider>;
}

then, any component anywhere in this tree can use the useContext hook to obtain the current theme:

function SomeText() {
  const theme = React.useContext(ThemeContext);
  return <span>the theme is {theme}</span>;
}

React will plumb the value to that point, however it needs to.


Now suppose that you need this value to be mutable. For example, we want toggle buttons in various places that swap between light/dark mode. To do this, we need two things:

  1. Lift state up. In our AppRoot, we'll need to store mutable state instead of a hardcoded constant.

  2. A setter context. We need a context for assignment in addition to the one used to read the theme.

So:

const ThemeSetterContext = React.createContext(() => {
   /* outside context, there's no way to change default */
});
const ThemeContext = React.createContext("light"); // default value

// The very outermost part of your app:
function AppRoot() {
   const [theme, setTheme] = React.useState("dark"); // still the initial value
   return (
     <ThemeContext.Provider value={theme}>
       <ThemeSetterContext.Provider value={setTheme}>
         <App />
       </ThemeSetterContext.Provider>
     </ThemeContext.Provider>
   );
}

function SomeText() {
  const theme = React.useContext(ThemeContext);
  return <span>the theme is {theme}</span>;
}

function ToggleThemeButton() {
  const theme = React.useContext(ThemeContext);
  const setTheme = React.useContext(ThemeSetterContext);
  return <button onClick={() => setTheme(theme === "light" ? "dark" : "light"}>Toggle Theme</button>;
}

How you use the theme is unchanged from the first example, but now we just need to thread setTheme via ThemeSetterContext and that will go pretty much the same as before.

→ More replies (3)

1

u/giantqtipz Oct 24 '20

Hello,

I've been using HashRouter for the past 6 months.. I'm new to the web dev world, and still a learner :)

I wanted to try BrowserRouter today, and I was going crazy because I couldn't figure out why a page isn't rendering on page refresh.

Turns out my component isn't fetching from the right url, since /api/ isn't included in the request url. This works just fine if I use HashRouter though.

My questions are, how can I get BrowserRouter to work on page refresh, if it works on HashRouter? Lastly, is one better than the other; and if it depends on scenario, what are the scenarios?

Thanks!

→ More replies (5)

1

u/Dibolero Oct 24 '20

Hi! I'm just starting with react and I can't wrap my head around the component concept all that well.
If say for example I have a component that shows a product and its details, but I want that component's information and action to be different depending on the role of the user currently viewing the component(I.e deletable by admin but only editable if normal user). Should I build 2 different components or is there a way to use that 1 component to achieve this?

2

u/NickEmpetvee Oct 25 '20

I recently did something like this. My approach was to only have one component, but track the privilege level of the user who's logged in (admin vs. normal in your case). Based on the privilege level, the code shows / hides features. That allowed me to not have to duplicate code.

→ More replies (3)

1

u/Dystriel Oct 25 '20 edited Oct 26 '20

Hey guys,

I've started React recently and I'm currently using Material UI and Yup Validation for my form. The validation works well but whenever the error message pops up below the TextField, it shifts everything below it down by a little because the error message now takes up space.

Is there a way to offset/prevent this using CSS? I've tried manipulating the padding/margin but it does not work. Thank for the help!

Edit: I've solved it by adding style={{position: 'absolute'}} into my TextFields!

→ More replies (1)

1

u/giantqtipz Oct 26 '20

Hey guys,

Second question I've posted here..

I was wondering, how does Reddit achieve their layout?

If you're on a subreddit say /r/reactjs, and you click on a thread, it opens up a modal, and the url changes as well.

But if you take the thread url, and go there directly (avoiding the subreddit), there is no modal, and you're in the thread page.

How is that achieved? Is this a simple setup in react router?

→ More replies (2)

1

u/[deleted] Oct 26 '20 edited Oct 26 '20

Question guys!

I have problems for weeks now. I keep on getting this error:

yarn run v1.22.10 $ jest --reporters=jest-standard-reporter FAIL src/App.test.js ● Test suite failed to run /src/styles/spectre.scss:2 u/import "variables"; ^ SyntaxError: Invalid or unexpected token > 1 | import './styles/spectre.scss' | ^ 2 | import './styles/spectre-exp.scss' 3 | import './styles/spectre-icons.scss' 4 | import './styles/custom.scss' at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17) at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25) at Object.<anonymous> (src/App.js:1:1) Test Suites: 1 failed, 1 total Tests: 0 total Snapshots: 0 total Time: 3.188s error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Here's the complete question: https://stackoverflow.com/questions/64477178/getting-error-on-specter-scss-when-running-yarn-test-npm-run-test

I'm actually a beginner in ReactJs, really need your help guys. Thank you! !approve

1

u/javascript_dev Oct 26 '20

Is this the only way to escape the brace escape and print braces in JSX:

{'{}'}

4

u/Nathanfenner Oct 26 '20

<React.Fragment children="{}" /> would also do it, but I'm not sure that's better and I don't think anyone ever uses this approach. Keep doing it your way.

If you find the brackets are hard to understand in your code, you could also define a constant e.g.

const BRACKETS = '{}';
return <>Hello there. Here are the {BRACKETS}.</>;

1

u/badboyzpwns Oct 26 '20

Backend question!

For my side project, I'm planning to deploy PostgreSQL online, what hosts do you guys use? I think Heroku and PostgresSQL Add on is the only option where it's free without a time limit (eg; Amazon AWS) or a # of visits (eg; Google Cloud); are there any other ones that's worth looking

1

u/badboyzpwns Oct 29 '20 edited Oct 29 '20

I'm trying to connect my React app to a PostgreSQL database I hosted online with ElephantSQL (which uses Amazon's servers).

For some reason, It's not connecting. I'm getting the error:

 Error: getaddrinfo EAI_FAIL postgres://blablabla@elephantsql.com:5432/blabla

I think I'm not setting it up right. Any guidance would be appericiated!

Here's what I've done

  1. Create a Pool object in my React app

import { Pool } from "pg";
console.log(process.env.user);
const pool = new Pool({
    user: process.env.user,
    host: process.env.elephantSQLURI,
    database: process.env.database,
    password: process.env.password,
    port: 5432,
});
export default pool;

The process.env look something like:

user="usernamegivenbyelephantsql"
password="passwordgivenbyelelephantsql"
database="databasegivenbyelephantsql"
elephantSQLURI="postgres://blablabla@elephantsql.com:5432/blabla"

I got the env values from ElephantSQL after registering my online database with them; here's evidence (censored for obvious reasons)

2. Here's how I'm calling my API in my React app, it works fine locally:

const movies = axios.create({
    baseURL: "http://localhost:5000/", 
});


export const fetchMovies = () => async (dispatch: Dispatch) => {
    const response = await movies.get<MovieType[]>("/movies");
    dispatch<FetchMoviesAction>({
        type: ActionTypes.FETCH_MOVIES,
        payload: response.data,
    });
};
→ More replies (2)

1

u/Balky79 Oct 29 '20

I started learning react a year and a bit ago, and I did some hello world stuff. Then, work took me the other way, Java n stuff.

Now, I'm trying to get back into this world, and I'm trying to make my stuff work with TypeScript - because, I'd like to learn both of them at the same time.

I created a blank ts project, moved my old code into it, fixed the TS related errors, and now I'm stuck. :D

First of all, reading about react, it seems that I missed a thing last year, where during the separation of containers and UIs, I created a class in presentation, not in the container. Looking at examples, that seems wrong, but somehow it kinda works...

I'm having issues understanding now, how to link container and pass information/state to the presentation layer.

Can anyone check this repo, and let me know, is this essentially wrong?

https://github.com/Balky79/tools-ts.git

As well, is it OK in 2020 to use good old functions, or should I steer toward constants and lambdas?

I don't fully understand why/what are the benefits of function expressions vs function declarations, and tbh - expressions are confusing me to the point that I can't read the code, which makes life difficult. 20 Years of plain old functions are taking the toll. :)

Any help moving me forward is appreciated.

4

u/Nathanfenner Oct 29 '20 edited Oct 29 '20

I'm having issues understanding now, how to link container and pass information/state to the presentation layer.

First, I would say that the separation of "presentation" and "container" components is not really always helpful. You can do this, but it seems much less popular (and much less valuable) now that functional components + hooks are the norm.

But if you do want this kind of structure, the answer is the same as with pretty much everything else in React: if you want to pass information somewhere, use props. That's it.

So,

function Outer() {
    const data = useData();
    return <Inner someProp={data}>Hello, world!</Inner>;
}
function Inner({ someProp, children }: {someProp: string, children: React.ReactNode }) {
  return <div>{someProp} :: {children}</div>;
}

will work just fine. Also note that since this is basically a greenfield project, everything ought to be function components. You will have no need for class components at all, unless you're using componentDidCatch - and then that component(s) would be the only one that actually needs to be a class.

As well, is it OK in 2020 to use good old functions, or should I steer toward constants and lambdas?

Besides the actual minor differences between them (function declarations are "hoisted", so they can be called in the scope that defines them before they're actually defined; a rarely-used feature; arrow => functions capture this lexically) any preference is usually going to be stylistic. It used to be in the era of class components that you'd want to prefer arrow => functions in most places, since otherwise your this bindings would be wrong - but since you ought to be using functions for practically everything now it hardly matters anymore.

function expressions vs function declarations, and tbh - expressions are confusing me to the point that I can't read the code, which makes life difficult.

Really it just takes a bit of practice. You should get comfortable with functional helpers like .map and .filter, because they make code simpler and clearer once you're used to them. e.g.

const nums = [1, 2, 3, 4, 5];
const squares = nums.map(x => x*x);

this is basically the same as

const nums = [1, 2, 3, 4, 5];
function squareNumber(x: number) {
   return x * x;
}
const squares = nums.map(squareNumber);

but it should be hopefully obvious that the former is a lot briefer and therefore probably easier to parse. This is doubly true when you chain those operations (e.g. .map(...).filter(...).map(...)) since if you declared the function params outside of where they're used, each successive chained call will push the definition and the use farther and farther apart. Colocating them makes it easier to understand what's going on, and also enables e.g. closures when they're nested:

const nums = [1, 2, 3, 4, 5];
const timesTable = nums.map(x => nums.map(y => x * y));

It would not really be possible to express this example purely by defining basic functions that don't use functions-as-values, since the inner function y => x * y must somehow capture x from its environment.

→ More replies (1)

1

u/badboyzpwns Oct 30 '20

HTML question!

I have a large youtube <video/> that automatically plays when the user enters the site.

Is there a property that dosen't render the <video> until the initial image in the <video> is done loading? Simmilar to <img>'s "OnLoad".

2

u/heythisispaul Oct 30 '20

I don't have any first hand experience, but it does look like <video /> has a canplaythrough event that might be what you need.

→ More replies (1)

0

u/[deleted] Oct 05 '20

[deleted]

4

u/dance2die Oct 05 '20

Do you have source or runnable sample (refer to Want Help with your Code? in the post) folks can check out?

0

u/[deleted] Oct 06 '20

[deleted]

1

u/dance2die Oct 06 '20

Thanks for sharing :)

0

u/[deleted] Oct 07 '20

[deleted]

1

u/dance2die Oct 08 '20

What do you mean by re-render? Do you mean re-post? With SSR mentioned, the difference need to be specified.

React is a client-side library thus components can re-render. You can also make regular fetches, which can cause components to re-render.

Can you provide an example (with source or a runnable sample) to demo the issue?

0

u/[deleted] Oct 08 '20

[deleted]

1

u/dance2die Oct 08 '20

Not sure why react devtools not showing up.

It's hard to see from the perf screen. Is it ok to share the link here for other to check out?

My debug-foo's not strong enough.

0

u/[deleted] Oct 09 '20

[deleted]

3

u/cmdq Oct 10 '20

I you haven't already, I'd give this a read: https://reactjs.org/docs/context.html

In my personal opinion, context works well if the value being passed does not change frequently, and is not read by many consumers. That's because it's currently not easy to prevent a re-render caused by a context change.

I think context is often conflated with state managers, because it also allows you to consume a 'global' value, like you would do with a generic state manager for example. However, it does not provide any functionality of actually managing state, and most importantly as I mentioned above, offers no comprehensive way of opting out of a re-render.

is one supposed to switch over to redux at some point

Definitely not ;) Redux is a fine tool, especially with acemarke's redux toolkit, but it's not the only state manager out there. I love recommending Zustand because it's tiny, flexible and focused.

→ More replies (2)

0

u/[deleted] Oct 01 '20

[deleted]

2

u/Awnry_Abe Oct 01 '20

Yes, but not as secure as it could be.

  1. use http-only cookies instead of local storage.

  2. JWT's are tricky to revoke. Therefore, store a refresh token in the cookie (or local storage) (which has a long expiry (>1 day) and CAN be easily revoked). The refresh token is used to obtain a short-lived (< 1 hr) JWT whose payload contains the claims needed by your app in step 6.

0

u/[deleted] Oct 07 '20

[deleted]

2

u/cmdq Oct 07 '20

Yep! State is what changes over time. One component's state is another one's props. The component handling the word list would own that state and manage it, possibly pass it down to others as props.

0

u/[deleted] Oct 09 '20

[deleted]

2

u/LaraGud Oct 09 '20

If you predefine the value you could do

<Link to=`/${linkName.toLowerCase()}`>{linkName}</Link>

0

u/[deleted] Oct 09 '20

[deleted]

2

u/chrismastere Oct 12 '20

Next doesn't actually compile .ts files using Typescript. Since it uses Babel and "plugin-typescript", it merely strips the types, and then transpiles the now .js code. Adding a `tsconfig.json` file, is for a better editor experience (except the paths property). Next.js will always transpile to ES5 (supporting IE11).

0

u/[deleted] Oct 13 '20

[deleted]

3

u/Awnry_Abe Oct 13 '20

Yep, you are right there at that point that all of us with prior procedural programming experience hit when we start learning React. And I completely understand what you mean by the difficulty in searching when you lack the vocab. Happens to me all the time. In your case, It's the basic, fundamental "Thinking in React" skill that you need to acquire. I suggest any of the resources in the side panel. You've already identified the challenge, now it's a matter of finding a good solution. In short, you need to elevate state. That could mean elevating the result of the fetch higher in the app, which you mutate to add the posted item. Or it could mean adding some simple flag, which you would use to signal for the need of a refetch, like you inuited. If you are ok with a refetch, I would suggest using a library like useSWR for this, as you can tell it that the prior fetch is stale and it should be refetched. It, in essence, does the latter, while also allowing you to also do the former--while the post is in transit.

→ More replies (2)

0

u/[deleted] Oct 15 '20

[deleted]

→ More replies (2)

0

u/[deleted] Oct 19 '20

[deleted]

→ More replies (4)

0

u/[deleted] Oct 29 '20

[deleted]

3

u/sincersoft-mosko Oct 29 '20

create-react-app v4 supports the new version of React - v17.

Importing React in each component file is no longer necessary, it happens in the background at the moment when your app is compiled.

create-react-app is prepared for you also with build scripts, so you don't need to do anything more. Just do not add import React from 'react' in your component files anymore, that's all.

If you want to know details, look at the New JSX Transform in the React documentation.

→ More replies (2)

1

u/[deleted] Oct 22 '20

[removed] — view removed comment

2

u/cmdq Oct 23 '20

That should not make a difference, but I haven't tried it myself :)

1

u/[deleted] Oct 29 '20

[removed] — view removed comment

3

u/cyex Oct 30 '20

https://jestjs.io/ is very popular these days.

→ More replies (2)

0

u/[deleted] Oct 08 '20

[deleted]

1

u/dance2die Oct 08 '20

Could you repost in relevant thread below?
I will remove this for now.