r/reactjs •

Beginner's Thread / Easy Questions (May 2020)

[deleted] — view deleted post

0 Upvotes

401 comments sorted by

6

u/badboyzpwns May 11 '20

about hooks, why do we use const when declaring the variable? especially if we are planning to change it later? For example,

 const [offset, setOffset] = useState(0);
setOffset('hi');

0

u/[deleted] May 11 '20

[deleted] — view deleted comment

4

u/badboyzpwns May 11 '20

Ahh thank you for the detailed explanation! makes sense!!

0

u/[deleted] May 10 '20

[deleted] — view deleted comment

2

u/PhilipRegular May 13 '20

Probably using Docker and something like Strapi.

3

u/[deleted] May 01 '20

I'm currently learning React through https://fullstackopen.com/en (nice open university course from finland for anyone interested)

Looking for help with custom hooks. So I have a custom hook which handles a forms state like so:

export const useField = () => {
  const [value, setValue] = useState('')

  const onChange = (event) => {
    setValue(event.target.value)
  }

  const reset = () => {
    setValue('')
  }

  return {
    value,
    onChange,
    reset,
  }
}

importing useField into the app to be used as follows:

const handleSubmit = e => {
    e.preventDefault();
    props.addNew({
      content: content.value,
    });
  };
  const handleClear = () => {
    content.reset();
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          content
          <input {...content} />
        </div>
        <button>create</button>
      </form>
      <button onClick={handleClear}>reset</button>
    </div>
  );
}

the spread operator {...content} throws a warning: Invalid value for prop `reset` on <input> tag.

The question is how can I maintain use of the spread operator while also fixing this problem?

I feel like it is an easy fix that I am just not seeing. If you wish to see the problem in full and most likely explained better its bottom of this page https://fullstackopen.com/en/part7/custom_hooks question 7.6

Thanks in advance all

0

u/[deleted] May 01 '20

[deleted] — view deleted comment

1

u/[deleted] May 01 '20

Awesome thanks, I was trying to modify reset like this { reset: null, ...content } and of course banging my head!

3

u/Hefticus May 01 '20

The other answer is perfectly valid, but I would caution against actually doing it. I've seen real-world bugs where a similar pattern is used and then in the future someone plucks out another specific field, so now that field is no longer present on the "content" object and doesn't get passed down as a prop. There could also be the opposite situation of more fields being added to content and then needing to be plucked out.

It may seem more verbose, but it's usually going to be better to just explicitly set every prop.

This seems like a case of whitelisting vs blacklisting, and in most cases whitelisting is better because it's less prone to surprising behavior and bugs in the future.

3

u/Fienases May 11 '20

is it good to write your logic inside your context component?

here's an example: https://pastebin.com/e9Tr3Etm

3

u/GhostofBlackSanta May 28 '20

How does rerendering work when setting multiple states? For example when I have a button with an onClick that calls a function that has multiple setState hooks, does it rerender for each setState or does it go through everything and then rerender all at once?

2

u/Nathanfenner May 28 '20

The updates are sent into a queue to be executed "soon". This triggers rerenders.

When the component re-renders, it applies all of the updates that were sent since the last render, in sequence (to the extent that makes sense). This is noticeable in useReducer, since it uses the reducer from the new render to actually apply the actions dispatched from previous renders.

So you'll generally only get 1 rerender, like you'd expect for reasonable performance/responsiveness. However, with Strict Mode enabled in development, React will always double-render everything to try to catch bugs caused by the incorrect use of side effects during render.

0

u/[deleted] May 28 '20

[deleted] — view deleted comment

1

u/GhostofBlackSanta May 28 '20

So if I have a function

Const func = () => {setCount(1); setName(“bob”)}

When this gets called, it’s going to run the line “setCount(1)”, rerender, then run setName(“bob”) and rerender again?

0

u/[deleted] May 28 '20

[deleted] — view deleted comment

1

u/GhostofBlackSanta May 28 '20

Ahh I see. Looks like it automatically batches when inside if an event handler but outside of that, you have to use unstable_batchUpdates. Thanks!

2

u/badboyzpwns Apr 30 '20

why do you have to use a class for redux-form? I tried building it with a functional component and it re-renders/makes me unfocus the input. These 2 examples below are the exact same code! but I demonstrated both with a class and a functional component.

Class:

class StreamCreate extends React.Component {
    renderInput = ({ input, label, meta }) => {
        return (
            <div>
                <input className="createInputs" {...input} autoComplete="off" />
            </div>
        );
    };
    render() {
        return (
            <React.Fragment>
                <div className="createTitle">Create Stream</div>
                <form>
                    <Field name="title" component={this.renderInput} />
                    <Field name="description" component={this.renderInput} />
                    <button>Submit</button>
                </form>
            </React.Fragment>
        );
    }
}
export default reduxForm({
    form: "streamCreate",
})(StreamCreate);

Functional component

const StreamCreate = (props) => {
    const renderInput = ({ input, label, meta }) => {
        return (
            <div>
                <input className="createInputs" {...input} autoComplete="off" />
            </div>
        );
    };

    return (
        <React.Fragment>
            <div className="createTitle">Create Stream</div>
            <form>
                <Field name="title" component={renderInput} />
                <Field name="description" component={renderInput} />
                <button>Submit</button>
            </form>
        </React.Fragment>
    );
};

0

u/[deleted] Apr 30 '20

[deleted] — view deleted comment

1

u/badboyzpwns May 01 '20

Thanks for the explanation! does it matter which I use at the end of the day?

And what do you mean by "wrapping renderInput with an array"? I'm a bit confused!

0

u/[deleted] May 01 '20

[deleted] — view deleted comment

1

u/badboyzpwns May 02 '20

Ahh thank you so much!!

For curisioity sake, when does redux-form re-render?, I'm guessing every user interaction causes a re-render? such as a person clicking it, clicking outside the form, typing inputs into it, correct?

2

u/Jorick_DC May 02 '20 edited May 02 '20

hello I am trying to create an application where users only see profiles with whom they match. however, I have no idea how best to approach this matching. Do you have any tips or tutorials explaining this?

as a database I use Firebase.

thank you for youre time. :)

1

u/cmdq May 10 '20

This is a pretty broad question ;) But in general:

I'd start with defining match criteria. Each matched criteria is worth a number of points, weighted by relevance. For each user you iterate through, compare each criteria and sum up the points. After you're done with the list, sort by point value and select the top X candidates.

2

u/Jorick_DC May 13 '20

Sorry for the question I will try to be more specifick next time! I would like to thank you for the advice. :) Now i have a general sense of what i must do.

2

u/pruggirello May 02 '20

Hey fellas!

I'm making a sudoku-ish game, where the player has to guess what numbers are in the grid based on hints they receive about the numbers' mathematical relationships. So far so good, but now I've hit a snag. Below is the structure for the <Hints /> component

displayHints = () => {
        let hints = this.props.game.getHints();
        console.log(hints); //this outputs new hints to the console each time it gets called
        return hints.map(hint => ( <p className="hints">{hint}</p> ));
    }

    generateNewHint = () => {
        //let hint = this.props.game.newHint(this.props.difficulty);
        let hint = this.props.game.addHint();
        this.props.game.setHint(hint);
        this.displayHints();
    }
render() {
        return(
            <div className="hint-container">
                <body className="hint-body">
                    <div className="hint-list">
                        {this.generateNewHint()}
                        {this.displayHints()}
                    </div>
                    <div className="spacer"></div>
                    <div>
                        <button className="hint-btn" onClick={this.generateNewHint}>Get another Hint</button>
                    </div>
                </body>
            </div>
        );
    }

this.props.game is a reference to my new Game() in my App.js, which I have here:

constructor(props) {
    super(props);
    this.state = {
      difficulty: "easy",
      hints: []
    }
    this.game = new Game(this.state.difficulty);
  }

This new Game() refers to my Game.js file which holds all the game's logic: the masterValues, userInputs, and the hints. The methods inside of Game.js, setHint() and getHints(), work perfectly for setting and getting new hints. Everything works, except I can't get my new hints to render. In my Hints component's render() function, I'm calling this.displayHints() to list the available hints, which works when the first one gets generated at the beginning of the game. After the user clicks the button, however, new hints are not being displayed even though I am calling the function again inside this.generateNewHint(). The console.log() is working and listing the appropriate hints. That's problem 1.

To solve this problem: I have tried switching .map and .forEach, I have tried setting hints to the <Hints /> state, and I have tried setting hints to the App.js state object. Neither .map nor .forEach works to render the new hints, just the first one. The latter two solutions didn't refresh the component when setState was called, which resulted in the new hints not being rendered.

Problem 2 is that my hints say "The number in [object Object] plus the number in [object Object] equals 0." It should be getting the key of the key/value pair for each individual number. This is should be something like A3, B1, C4, D2, etc. This corresponds to a square on the board at row Letter and column Number. The hints should read: "The number in A3 plus the number in C1 equals (sum of the two numbers)". The object that gets passed in looks like this: {A1: 24} The key is dynamically set and the value is randomly generated and then assigned.

So my quesitons are: 1. How can I get my list of hints to be rendered dynamically? What's the best way to do it? 2. How can I access the key and the value in my hint objects separately?

1

u/cmdq May 10 '20

From what I can spot without seeing the whole App, there's a couple of fundamental issues. Do you have a background in regular (imperative) game programming? Your approach looks very imperative to me: getting, setting, calling methods to show display hints.

React wants things to be done declaratively. Instead of telling a thing to go do some thing and then render that thing, you abstract things that change into state. This state becomes a child's props. When your state changes, the tree below you re-renders with new props.

Also, rendering is not imperative. Instead of telling your app 'go display hints' you describe what the world should look like, given your props.

render() {
  return (
    <ul>
      {this.props.hints.map(hint => (
       <li>{hint}</li>
      ))}
    </ul>
  )
}

Problem #1:

generateNewHint should be either be a function that updates your local state, a parent's state, or some otherwise global state. It should cause a new hint to be added to the array of existing hints. This change will cause your component to re-render and use the updated hints prop.

Also this.displayHints() returns new hints to nowhere, as you're not using the result. Rendering in react only renders what is being returned inside render() { return yourStuffToRender }.

Problem #2:

Currently, JavaScript coerces your object into a string. This happens via the .toString() method which for objects just returns [object Object]. It's not entirely clear how your data is set up (where do the two keys come from?) but it could look something like this:

(keyA, keyB, gameState) => `
  The number in {keyA} plus the number in {keyB} equals {gameState[keyA] + gameState[keyB]}
`

1

u/pruggirello May 14 '20

Hey! Thanks for your reply! I understand what you mean with the states, but I don't know how to pass a state to a componentless js file. The Game.js file is supposed to hold all the game's logic, which is why I'm passing data like that. I don't need Game.js itself to render anything. Can I just have it return an empty <div /> ? If that's allowed I could easily change this to a React component and pass the state values as props.

As for the second problem, I could potentially just destructure the data and use backticks?

1

u/cmdq May 14 '20

Hm, your setup sounds a bit funky. Could you please put the entire app on codesandbox?

1

u/pruggirello May 16 '20

Hey, thanks for your response! I haven't forgotten about it, just been a little busy. I hope to upload it today or tomorrow.

2

u/masterofmisc May 03 '20

Hi Guys,

I know that react is all about components and building them up. But I am stuck on how you lay them all out to fit your design on paper.

For example, say I want to make an Outlook clone with a tree view on the left and on the right side of the page, have it split horizontally. The top half would be a list of emails and the bottom half would be the email detail. Then at the top of the page, have tabs to flip between inbox, sent items, calendar, etc. When you click on a different tab it could totally change the contents of the main page.

In my mind I can see how to make all the individual components that do each thing, but I don't know how you would put them all together? How would you guys go about doing this? Is there a package you pull in?

Or do do you use a grid system? But then if its a grid system, how would you make the tree view panel resizable for example? (or is that advanced)

Thanks in advance.

2

u/moscowramada May 06 '20

The tabs is a great use case for a UI library. The major ones, like semantic UI, definitely support them. I would do that rather than roll my own tabs (ugh).

To have it split horizontally - that sounds like 'width: 30%' for one div and 'width: 70%' for the other, with something like 'display:inline-block' (or whatever it is, please look that part up).

And I would use media-query to send different layouts to desktop and mobile.

1

u/masterofmisc May 07 '20

Thanks. Just looking at semantic UI now.

2

u/cmdq May 10 '20

for your specific use case, check out https://github.com/zesik/react-splitter-layout

2

u/masterofmisc May 10 '20

Oh this is brilliant. Its exactly what I was looking for. Thank you.

2

u/dlrwtllktgrtt May 04 '20

I've deployed a React app talking to a Firebase Firestore DB using Amazon's Amplify service.

My Firebase API keys are defined in the AWS console as environment variables.

My question is: Is this a secure way of doing this? or are my Firestore API keys and other secrets accessible for someone who chooses to go through the compiled files in a browser?

I found this in the React documentation that has me confused:

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

Edited for clarity.

0

u/[deleted] May 04 '20

[deleted] — view deleted comment

3

u/dlrwtllktgrtt May 04 '20

I did search the bundle, and yes the keys are all public in the bundle being served up, Amplify doesn't generate lambdas to handle this.

I've since discovered that the API keys are meant to be public.

Here's what the firebase docs had to say:

The content is considered public, including your platform-specific ID (entered in the Firebase console setup workflow) and values that are specific to your Firebase project, like your API Key, Realtime Database URL, and Storage bucket name. Given this, use security rules to protect your data and files in Realtime Database, Cloud Firestore, and Cloud Storage.

The approach then is to use security rules along with firebase auth to make sure no unauthorised person can read, write, modify or delete data.

A simple rule for eg can be:

allow read, update, delete: if request.auth.uid == userId;

more examples in the security rules docs I've linked to above.

2

u/Jorick_DC May 04 '20

Hi,

I am trying to create a registration page. I am already able to write data to Firebase database. However, I get stuck when I want to upload the profile picture to firebase and save the reference in Profile on the database. Does anyone have a good tutorial or tips for this?

Thank you for your time :).

1

u/cmdq May 10 '20

Did you already have a look at this: https://firebase.google.com/docs/storage/web/upload-files

If yes, can you explain what you get stuck on?

2

u/Luke_Mudufi May 04 '20

So having this weird problem where my react app isn't showing anything to the browser and I'm not sure why it was working fine before I'm working through a Bootcamp and learning react and im completing lost on how to fix it

1

u/careseite May 05 '20

whats the error in the console? that should always be your first step if something explodes

2

u/Ret_01 May 04 '20

I've recently been tasked with providing a new React based UI to an existing WebGL application (currently using Knockout) and am having some trouble figuring out how to handle sharing state between the UI and the WebGL application. The application must be able to trigger UI updates and vice versa.

So far I've tried to use the useEffect hook, which lets the UI update the application, but it requires diffing against previous state to detect when things have actually changed. I also have no idea how to get the application to update the UI without using an EventEmitter to trigger a full ReactDOM.render call.

Has anyone else had to deal with this sort of situation and if so how did you manage it? Are there any established patterns for dealing with it?

2

u/cmdq May 10 '20

I'd do it this way:

use https://github.com/react-spring/zustand as external, global state. React uses this state via useStore().

Then, use the second element of the returned tuple (api in the readme) to access your state setter methods of the store when settings get changed in the WebGL app (api.getState().mySetterFunction()).

Then, use api.subscribe() to apply changes from the store to the WebGL app.

This way, changes only flow from the store down to react and WebGL.

2

u/Ret_01 May 10 '20

I've settled on a custom bridge that can pass commands back and forth and allows for easy undo/redo. The WebGL application needs to keep control of it's internal state ultimately for performance reasons. Thanks though.

2

u/ytdl-node May 09 '20

If I am using React hooks, let's say for a state change, I'd normally write something like:

// In function App()
const [username, setUsername] = useState('');
const [age, setAge] = useState(0);

console.log(username, age);

Now if I pass the setUsername and setAge functions to a component let's say 'A' in the following fashion:

<A setUsername={setUsername} setAge={setAge} />

And in my component 'A', I update the username and the age.

function A(props) {
    const { setUsername, setAge } = props;
    setUsername('user');
    setAge('5');
}

This will cause the main App to re-render twice right? Is it not better if I just use an object for the state? E.G.:

const [state, setState] = useState({
    username: '',
    age: 0,
});

Why do we not use this instead?

1

u/dance2die May 09 '20

You can use useReducer should you need to update multiple states at once. Pass down a dispatch or an "action" calling dipsatch down to a child component would work.

1

u/cmdq May 10 '20 edited May 10 '20

it doesn't re-render twice

react applies state changes asynchronously and batches calls, so multiple chained calls do not result in excessive re-rendering

i'd encourage you to always challenge your initial assumptions, especially when it comes to perceived performance issues :)

0

u/[deleted] May 12 '20

[deleted] — view deleted comment

1

u/Awnry_Abe May 12 '20

To get the sorted list from B to C, it would need to go through A. So A would expose a "setSorted" method to B as a prop. A would pass the value as a prop down to C. This is going to leave you with A holding both the unsorted and sorted lists.

1

u/cmdq May 12 '20

It'd be good to see some code so we can actually give you an informed answer. Until then, my guess is that you're changing the data somehow in class B.

There is no manual synching in react, the data that drives display of B and C should live above them, possibly in the nearest ancestor A. A holds this data as state and passes it to B and C as props.

Because B needs a way to change this data, but should not mutate it locally, access to the mutation logic should come from A in form of some method which mutates the data and then updates state on A via setState. This method is passed from A to B as props.

B calls this method and causes A and its children to re-render. This re-render occurs with the new state, which gets passed to B and C as props.

Now all components are in sync, because the updated data flowed downwards.

2

u/badboyzpwns May 12 '20 edited May 12 '20
                        <button className="blackButton">
                            <Link to={`/streams/edit/${stream.id}`}>
                            <h5> Edit </h5>
                             </Link>
                        </button>

Problem is, I have to click the button twice in order for <Link> to be triggered.

Putting <Link> outside <button> makes the anchor tag/<Link> not inherit the button's width/height.

Any workaround for this? Is there a react property that i could use or is this more of a css thing?

4

u/MatisLepik May 12 '20 edited May 12 '20

The purpose of a button is to have a clickable thing that triggers some javascript (or a form). You're not allowed to nest clickable things, so putting a Link inside a button is not allowed.

You should use class names to give your link the correct styles.

1

u/badboyzpwns May 12 '20 edited May 12 '20

Thank you!! any suggestions on how to style it? Since the button has a margin-right, the <Link> seems to inherit too.

Looks like this: https://codepen.io/mattfrancis888/pen/pojZjWZ

How would you avoid it?

1

u/MatisLepik May 12 '20

I'm not sure what you're trying to accomplish. The codepen still has a button inside an anchor element, which is also not allowed. You should use one or the other, not both.

1

u/badboyzpwns May 12 '20

My bad! I'm trying to re-direct users via a button when clicked.

> The codepen still has a button inside an anchor element, which is also not allowed.

How would you do it with a button and <Link> on React then? I saw a tutorial doing it with <Link> wrapping the button, so I'm just following it!

0

u/[deleted] May 12 '20

[deleted] — view deleted comment

1

u/badboyzpwns May 12 '20 edited May 12 '20

My bad! <Link> does inherit it! but I added a margin-right to the button and it also inherits the margin! Looks like this:

https://codepen.io/mattfrancis888/pen/pojZjWZ

How would you "stop" it from inheriting the margin?

EDIT:

I also realized that you can just use <button onClick = history.push("")/>, does it matter which I use?

0

u/[deleted] May 12 '20

[deleted] — view deleted comment

1

u/badboyzpwns May 12 '20

ah thank you!! I was told that <Link> inside or outside a button is not best practice. I'm assuming it's because of issues like this.

But since you mentioned:

> it makes sense for that margin to be visible. You may want to reconsider your CSS.

Just a confirmation, I'm assuming you reccomend it? I managed to figure it out by setting <button> to display:block!

0

u/[deleted] May 12 '20

[deleted] — view deleted comment

2

u/badboyzpwns May 13 '20

Thank you!!! I decided to use history.push() instead of Link and it work wonders!!

2

u/[deleted] May 12 '20

Hi there, I'm new to React and am trying to create a workout tracker web application.

So far, I decided that when the app first starts, there will be a homepage that has 3 buttons: Create Workout, Select Workout, Stats. These options were created via the common component, WorkoutOptions.

Now, my goal is to be able to click select workout, and have a new Container component show up to replace the existing 3 buttons, essentially moving the user to the "next" page.

However, I'm unsure of how to do this.

In my head I'm thinking that if the App Component detects that selectWorkout is clicked (via event listener), it will render <Container/> and unrender(??) the Option Cards

However, that clearly doesn't sound right so pointers would be much appreciated

2

u/Awnry_Abe May 13 '20

Use the useState() hook in App to store the current selection. When there is none, show WorkoutOptions. App will pass a "selectOption()" prop to WorkoutOptions that is called with the value chosen in each button's onClick handler. The state setter returned by the useState hook will suffice in this case (as a learning experience). When you get your feet planted on solid React ground, look into react-router, which replaces the single piece of state in App with an app-wide piece of state stored as the browser's url. Using a router isn't necessary but makes life easier both as a developer and user when other features emerge.

1

u/[deleted] May 14 '20

I tried it out and woah was able to do some many more things! Thank you so much! I didn't even think to look into hooks because I was worried that stuff was too advanced for me! But given a clear example like that, I got it down! Thank you! I will look into react-router in the future too!

1

u/Awnry_Abe May 14 '20

Awesome. Good luck!

2

u/badboyzpwns May 15 '20

I'm planning to intern as a junior dev! Is it valuable to learn Testing such as using redux-saga, Jest, etc? (I don't see any job postings specifying that I need to do unit tests, etc) Or is this more of valuable asset for experienced senior devs?

0

u/[deleted] May 15 '20

[deleted] — view deleted comment

2

u/badboyzpwns May 15 '20

Thank you!! I'll definitely look into it :)

2

u/089-083 May 22 '20

Hey guys - I was able to build a small application that takes input, uses the input to call an api, and displays the results from the api. Let’s call this the platform.

How do I go about making another page, let’s say a landing page, where I can login and signup before being able to access the platform?

I have only used react for this application so far, nothing server side yet.

2

u/sacrecide May 22 '20

If you want to make a login page, youll have to do some server side work. Outside of sending the username and password to your server, the frontend should avoid any log in logic to avoid gaping vulnerabilities

1

u/089-083 May 22 '20

Cheers, what do you recommend I use for a backend and for the authentication flow?

2

u/sacrecide May 22 '20

I like C# MVC. Its free to use commercially, c# is basically java with more built in functions, and routing with MVC is easy to learn. Identity framework will handle most of the authentication for you. You'll probably want to set up some database as well, entity framework will give you a quick way to query the database in a way thats safe from sql injection.

→ More replies (1)

1

u/an732001 May 22 '20

You’ll have to use a react library like react router

2

u/[deleted] May 22 '20

Noobie here with a few questions, the first one is as simple as it gets and I thought I knew the answer to it. In the following code I expected to only log to the console once as the state is set before rendering and therefore a second render should not happen because the state never changes but rendered is logged twice.

const App = () => {
const [name, setName] = useState();
return <div>{console.log("Rendered")}</div>;
};
export default App;

The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.

2

u/Nathanfenner May 22 '20

React is allowed to render components extra times if it chooses to. In development with StrictMode all components are always rendered twice.

The second question I have no code example for but the issue I have is using the response from one http call as a part of another http call that immediately follows the first. I'm using async/await and putting the response in state but as setting state is async the second call starts using an undefined value. What's the best way to handle this? Thanks in advance for any help.

The async action part should happen in a useEffect call. The second fetch is for a second piece of state, so it should also happen in a second async call. Something like the following:

    function App({ id }) {
        const [profile, setProfile] = useState(null);
        useEffect(() => {
            setProfile(null);

            let stillCurrent = true; // tracks when unmounts/changes

            fetchProfile(id).then(result => {
                if (stillCurrent) {
                    setProfile(result);
                }
            })

            return () => {
                // cleanup function
                stillCurrent = false;
            }
        }, [id]);

        const [comments, setComments] = useState(null);
        useEffect(() => {
            setComments(null);

            if (profile === null) {
                return; // nothing to do yet
            }

            let stillCurrent = true; // tracks when unmounts/changes

            fetchComments(profile.commentIds).then(result => {
                if (stillCurrent) {
                    setComments(result);
                }
            })

            return () => {
                // cleanup function
                stillCurrent = false;
            }
        }, [profile]);
    }

Notice that I included some cleanup stuff, which you need to make your components robust to race conditions. For this kind of thing, a custom hook is helpful, so that your components can remain more "focused" on what they're supposed to be showing. E.g. something like

function useAsyncState(action, dependencies) {
    const [state, setState] = useState(null)
    useEffect(() => {
        setState(null);
        let stillCurrent = true;
        action().then(result => {
            if (stillCurrent) {
                setState(result);
            }
        });
    }, dependencies)

    return state;
}

function App({ id }) {
    const profile = useAsyncState(async () => {
        return await fetchProfile(id);
    }, [id]);
    const comments = useAsyncState(async () => {
        if (profile === null) {
            return null;
        }
        return await fetchComments(profile.commentIds);
    }, [profile]);
}

This isn't really complete (for example, no error handling) but it gives a good idea of how you can make this look. There are React hook libraries already out there for doing this sort of thing, but I can't vouch for any in particular.

1

u/[deleted] Jun 01 '20

This solved both my issues, thanks again for the help

2

u/Guisseppi May 23 '20

Both issues you’re experiencing are called “side-effects”. Basically for your first problem you have to wrap console.log on a useEffect hook, the second one could be solved in the same way but it gets cumbersome to say the least. When you’re dealing with several dependent side-effects, a good way to solve this is by using sagas, or if you just keep all the async calls within a scope and save the state later and avoid the race conditions all-together, just my 2 cents

2

u/Cannabat May 24 '20

I am working on a hobby project that has some very CPU intensive reducers in redux. I’d like to explore running those reducers in a web worker.

It looks like I could extract the reducer code to a module and use worker-loader + comlink + redux-thunk to do the work asynchronously.

Am I thinking about this correctly? This is a bit outside my comfort zone, appreciate any advice!

It may be simpler to not use redux and switch to context when using webworkers, but the redux dev tools and packages like redux-persist are really nice to have.

2

u/cmaronchick May 26 '20

What's the preferred way to fetch data when a user navigates via React Router?

My best assessment at the moment is that if you have a standalone page (ie a user can navigate directly to it), it's best to make it a class so that you can check the state and fetch data if the route parameters are updated, but I wonder if I am missing something obvious.

FWIW, I'm using Redux with React Router. Thanks in advance.

1

u/dvx8 May 27 '20

Do the fetching in the component that Router renders for a specific path, or any of its children that need the data.

Specifically in the component's useEffect(fn, []) or componentDidMount.

2

u/konaraddi May 28 '20

I have a simple component that React calls 2*(N+1) times where N is the number of state changes:

https://codesandbox.io/s/stoic-goodall-2tvxn?file=/src/App.js

Why does this run 2*(N+1) times (as opposed to N+1 times where N is the number of state change and +1 is from the initial render)?

2

u/Nathanfenner May 28 '20

You have StrictMode enabled. In development, all components render twice for each update, to help catch bugs related to side effects in render (which you should avoid).

1

u/konaraddi May 28 '20

Ah okay, thank you!

1

u/iTsHutchy Apr 30 '20

Im new to react - ive built a few static page websites (2-3 pages) looking how I can integrate with databases and expand my knowledge and learn what react can offer for my development is there any quick resources I can take a look at

5

u/muzkk May 01 '20

Hey, to integrate with a database you will be entering to the world of "full stack development" (that is what you should be looking for).

A "full stack developer" is someone capable of doing just what do you want to do: create a website that is connected to a database.

If you search about this term, you'll be stressed out about how many technologies you need to learn to do that :( because it is not as simple as running a line of code. Here is a small intro: https://academind.com/learn/react/connect-to-database/

I think the easier and fastest way to "connect a React app" with a "database" is by using Firebase (https://firebase.google.com/). There is a video from freecodecamp about this: https://www.youtube.com/watch?v=m_u6P5k0vP0

Good luck!

1

u/iTsHutchy May 01 '20

thanks ill check it out

1

u/[deleted] May 01 '20

Check out the freecodecamp project videos

1

u/carlsopar Apr 30 '20

I have a project that lets you place a text element onto an SVG. Once that element is placed, I then want it to be draggable so that it can be repositioned. currently, I can place the text element, and I can do edit it, however, when I go to move it, that is where I am having problems. Currently, the issue is that when I click and move a text element, it moves. But when I release and click again, the element will move on its own always to the same spot. When I go to click it, then it will move off the page entirely.

I have looked and attempted several different ideas including these sources:

https://dev.to/tvanantwerp/dragging-svgs-with-react-38h6

http://www.petercollingridge.co.uk/tutorials/svg/interactive/dragging/

I believe, it has to do with the fact that a mouseclick reads according to the whole page, but I need it to be a specific area.

This is my canvas element that has the SVG:

import React, { useState } from "react";

const SvgCanvas = (props) => {
  const [Dragging, setDragging] = useState(false);
  const [origin, setOrigin] = useState({ x: 0, y: 0 });
  const [coordinates, setCoordinates] = useState({ x: 20, y: 20 });

  const DragClick = (e) => {
    console.log(e.target.attributes);
    e.preventDefault();
    setDragging(true);
    console.log(e.target);
    setOrigin({ x: e.clientX, y: e.clientY });
  };
  const DragMove = (e) => {
    
    e.preventDefault();
    if (Dragging) {
      // var x = parseFloat(e.target.getAttributeNS(null,"x"))
      // console.log(x)
      // e.target.setAttributeNS(null,"x",x+.1);
      console.log("Origin= X: "+origin.x+", Y: "+origin.y);
    console.log("Current= X: "+e.clientX+", Y: "+e.clientY);
     setCoordinates({ x: e.clientX - origin.x, y: e.clientY = origin.y });
    }
  };
  const DragRelease = (e) => {
    e.preventDefault();
    setDragging(false);
  };
  var lnk = props.details.url;
  const TextBoxArray = [];
  for (var i = 0; i < props.details.box_count; i++) {
    //console.log("for");
    //console.log(props.Meme[i]);
    const y = '20';
    const x = '30';
    TextBoxArray.push(
      <text
        key={i}
        id={"MemeBox" + i}
        y={`${coordinates.y}`}
         x={`${coordinates.x}`}
        //transform={`translate(${coordinates.x}, ${coordinates.y})`}
        fontSize={props.Meme[i] ? props.Meme[i].range : "16"}
        fill={props.Meme[i] ? props.Meme[i].color : "black"}
        onMouseDown={(e) => DragClick(e)}
        onMouseMove={(e) => DragMove(e)}
        onMouseUp={(e) => DragRelease(e)}
      >
        {props.Meme[i]
          ? (document.getElementById("MemeBox" + i).textContent =
              props.Meme[i].text)
          : null}
      </text>
    );
  }

  return (
    <div id="SvgCanvas">
      <svg>
        <image key={props.details.id} x="10" y="10" href={lnk} />
        {TextBoxArray}
      </svg>
    </div>
  );
};
export default SvgCanvas;

And, the app.js file

import React, { useState} from "react";
import ReactDom from 'react-dom';
import SvgControls from "./components/svgcontrols";
import SvgCanvas from "./components/svgcanvas";
import MemeChooser from "./components/selector";
import "./style/meme.css";

function App() {


  const [Meme, setMeme] = useState([]);
  const [MemeText, setMemeText] = useState([]);
  const MemeSet = (e) => {
    setMeme(e);
  };
  const TextSet = (MemeEditArray, InitialArraySetFlag) => {
    if (!InitialArraySetFlag) {
      setMemeText(MemeEditArray);
    }
    if (InitialArraySetFlag) {
      var MemeEditArrayCopy = [...MemeText];
      MemeEditArrayCopy[MemeEditArray["id"]] = MemeEditArray;
      setMemeText(MemeEditArrayCopy);
    }
    
  };

  return (
    <div className="App">
      <header>Meme Maker</header>
      <div id="MemeMaker">
        <SvgCanvas Meme={MemeText} details={Meme} />
        <SvgControls getter={MemeText} setter={TextSet} details={Meme} Create={document.getElementsByName(SvgCanvas)} />
        <MemeChooser click={MemeSet} />
        {
        //console.log(ReactDom.findDOMNode(this).querySelector(SvgCanvas))
        }

        
      </div>
    </div>
  );
}

export default App;

I appreciate any suggestions, that you may have to help me fix this.

1

u/NickEmpetvee May 01 '20 edited May 01 '20

React 16.13.1 (via create-react-app that executed a few days ago)

Implementing a file upload prototype and using a tutorial. The below code yields a POST http://localhost:8000/upload/image 404 (Not Found) as a result of the await fetch. I've created a folder '/upload/image' under '/src' and '/public' with the same result. Also tried changing the fetch target location to '/' with no love. No special configurations to node.

Also tried with AXIOS that yields

Failed to load resource: the server responded with a status of 404 (Not Found)
Huston we have problem...: Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)

Any ideas?

const api =
{
    async uploadFile (nextFile)
    {
      console.log('processing');
      console.log(nextFile.file);

      let user = { name:'john', age:34 };
      let formData = new FormData();
      let photo = nextFile.file;      
           
      formData.append("photo", photo);
      formData.append("user", JSON.stringify(user));  
      
      try {
         let r = await fetch('/upload/image', {method: "POST", body: formData}); 
         console.log('HTTP response code:',r.status); 
      } catch(e) {
         console.log('Huston we have problem...:', e);
      }
    },
}

2

u/[deleted] May 02 '20

404 means "not found". Uploading images requires something on the server listening to your upload request, and then writing that file to the filesystem. Since React is a client-side javascript library, your application is not able to do this. You can't simply make a POST request and expect the file to end up written somewhere.

In order to support image upload, you would need to implement a proper backend with something like php, or nodejs, but that is outside the scope of this thread :). The point is, CRA does not come with a backend, so you don't have anything listening for the "POST /upload/image" route, which is why you're getting back a 404.

1

u/NickEmpetvee May 02 '20

Thank you. I'm running my React project under nodejs (12.16.3) which you can get to through http://localhost:8000. Per what you're saying, nodejs doesn't handle something like this out of box. I incorrectly assumed it would. Do you know of a really simple way to set nodejs up so that it can handle file upload? BTW, my goal here is allow upload of PDF, DOCX, VSDX, SVG and images, but the tutorial only focuses on images hence what you see above.

→ More replies (3)

1

u/AmauryH May 01 '20 edited May 01 '20

Hello guys,It's not 100% React related, but I had no luck on a different sub.

I've almost finished Andrew Mead's course about React and I'm working on a small web app.

In short, it's a web ap to manage a collection of action figures.

My question concern my DB structure. I'll probably go with Firebase as it's the DB that is seen during the course.

What I need:

  • Multiple users
  • A common DB
  • Each user has a private "my collection" and a private "my wishlist"
  • On the DB page, there will be the possibility to filter and to sort using properties of the figures

What I'm about to use:

figures : {
    some_id: {  
        name: "name",  
        description: "description",  
        ...  
    },  
    some_id_2: { ... }  
},  
users : {  
    user_id: {  
        collection: {  
            some_id: "some_id",  
            some_id_2: "some_id_2"  
        },  
        wishlist: {  
            some_id: "some_id"  
        }          
    }  
}

I'm not used to decide the schema of the DB myself.

How does it sound to you ?

1

u/dance2die May 05 '20

Yeah. It'd be hard to get a reply on DB questions.

What would you think isn't working for the schema?

1

u/AmauryH May 05 '20

Well, as I'm not experienced with deciding my own DB, I would rather be sure to create something that will run smoothly.

My main concern is performance. I don't know it it will perform if I have to compare an array of 600 objects (figures = [{},{},...]) with another array (collection = ["0","1",...].

And I don't know how I feel about collection and wishlist. They should be an array, but I can't store an array in frebase and I don't know if there is a better solution than storing a fake key/value pair.

1

u/dance2die May 07 '20

Seems like Firebase converts an array into an object.

So maybe sending it off to as an array would work.
Performance depends on so many factors so you might want to try out your approach and modify as you go along.

1

u/AmauryH May 07 '20

The conversion works just fine. Thanks.

Now I'm wondering if I should group figures by Toy lines...

- figures
  - toyLine1
    - item1
    - item2
  - toyLine2
    - item1  

But I feel that it will add muche more complexity to all the search / sort features.

I guess that I'll try the way I've started and see how it goes.

Again, thanks for your help!

1

u/Jorick_DC May 01 '20 edited May 01 '20

Hello,

I have a quick question. I was following the tutorial below to build a multi step form with react hooks. but I don't understand why he uses <div> instead of <form>. and how you can send the data with onSubmit = (event) => {}. Thank you for your time.

I think I will need to use the effect hook to acces the api point to write the data to my database.

the tutorial: https://medium.com/javascript-in-plain-english/how-to-create-a-multi-step-form-with-react-hooks-53a85efdff62

0

u/[deleted] May 01 '20

[deleted] — view deleted comment

2

u/Jorick_DC May 01 '20

Thank you for explaining it go me! I am pretty new to react so i was really struggling tot understand the concept

1

u/maxfontana90 May 02 '20

I recommend using Formik

1

u/Jorick_DC May 02 '20

thank you for the advice! i will look it up :)

1

u/[deleted] May 01 '20

I'm trying out ant.design and I can't even figure out how to install it.

I saw this on npmjs.com -

npm i antd

I did this. After importing a component

import {Button} from 'antd';

I get this error

Error: Cannot find module '. /locale'

1

u/dance2die May 05 '20

Would you file an issue on their github repo?
https://github.com/ant-design/ant-design/issues

1

u/[deleted] May 05 '20

I figured it out. The problem was with the version of moment.js. Just had to force it to use an older version.

1

u/dance2die May 05 '20

Ah... that. I remember having to fix it at version 2.24.0 for the issue... Glad that it worked :)

1

u/plasmaSunflower May 01 '20

I’m trying to use emailjs with react hook forms and I can’t get them to work together, it seems like only one will work at a time. Need help.

1

u/dance2die May 05 '20

Hi u/plasmaSunflower.

Majority of communities usually frown upon or ignore questions that "asks for help".

The question's not specific enough for folks to reply. Refer to this on how to get a better reply.
https://www.reddit.com/r/reactjs/wiki/index#wiki_want_help_with_your_code.3F

1

u/Amerzel May 02 '20

If you were starting a new app and we’re using redux for state management would you use react-redux or @redux/toolkit?

0

u/[deleted] May 04 '20

[deleted] — view deleted comment

1

u/Amerzel May 04 '20

Oh really? I guess I need to take a closer look at them then. Thanks for the response!

1

u/deadcoder0904 May 02 '20

How to display an array of objects row-by-row using React Table?

I want to display movies row-by-row without changing the data model.

Here's my code:

import * as React from "react";
import { useTable } from "react-table";

const borderStyle = {
  border: "1px dashed navy"
};

export default function App() {
  const data = React.useMemo(
    () => [
      {
        actor: "Johnny Depp",
        movies: [
          {
            name: "Pirates of the Carribean 1"
          },
          {
            name: "Pirates of the Carribean 2"
          },
          {
            name: "Pirates of the Carribean 3"
          },
          {
            name: "Pirates of the Carribean 4"
          }
        ]
      }
    ],
    []
  );
  const columns = React.useMemo(
    () => [
      {
        Header: "Actor",
        accessor: "actor",
      },
      {
        Header: "Movies",
        accessor: (row, index) => {
          console.log({ row });
          // i want to display this row-by-row instead of in 1-row without changing data model
          return row.movies.map(movie => movie.name);
        }
      }
    ],
    []
  );
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({ columns, data });
  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()} style={borderStyle}>
                {column.render("Header")}
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          if (i == 0) {
            console.log({ row });
          }
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell, j) => {
                if (i == 0 && j < 2) {
                  console.log({ cell, i, j });
                }
                return (
                  <td
                    {...cell.getCellProps()}
                    style={borderStyle}
                  >
                    {cell.render("Cell")}
                  </td>
                );
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

It currently looks like:

codesandbox

Here's the direct link to it: https://codesandbox.io/s/modest-sanderson-z0keq?file=/src/App.tsx

My movie list is an array of objects so how will I display it beside actor name? So it looks like:

ActorMovies
Johnny DeppPirates of the Carribean 1
Johnny DeppPirates of the Carribean 2
Johnny DeppPirates of the Carribean 3
Johnny DeppPirates of the Carribean 4

1

u/Chawawis May 04 '20

You basically want to structure your table like this:

<tr>
    <td>Johnny Depp</td>
    <td>Pirates of the Caribbean 1</td>
</tr>
<tr>
    <td>Johnny Depp</td>
    <td>Pirates of the Caribbean 2</td>
</tr>
<tr>
    <td>Johnny Depp</td>
    <td>Pirates of the Caribbean 3</td>
</tr>
<tr>
    <td>Johnny Depp</td>
    <td>Pirates of the Caribbean 4</td>
</tr>

You're currently doing:

<tr>
    <td>Johnny Depp</td>
    <td>Pirates of the Caribbean 1
        Pirates of the Caribbean 2
        Pirates of the Caribbean 3
        Pirates of the Caribbean 4
    </td>
</tr>

So you'll either have to modify your data or your loop.

2

u/deadcoder0904 May 04 '20

Yep I'm modifiying the loop now. Data was scraped so won't be doing that again.

1

u/Chawawis May 04 '20

If you run into that situation again and you don't want to change your data, you could maybe update one of your accessors like:

{
    Header: "Actor",
    enableRowSpan: false,
    accessor: (row, index) => {
      return row.movies.map(movie => row.actor);
    }
},

Just food for thought..

1

u/[deleted] May 02 '20

Hi, I have a question about this counter component.

I click the button and the value of the button increments. Nice! But after I call setCounter(counter + 1); and callconsole.log("counter", counter);` on the next line, the output is always one value behind. How come? Is there a way to fix this? Thanks.

App.js

import React, { useState } from 'react';
import Button from "./Button";

function App() {

  const [counter, setCounter] = useState(0); 

  const buttonHandler = () => {
    setCounter(counter + 1);
    console.log("counter", counter);
  };

  return (
    <div className="app">
      <div className="deck-container">
        <Button buttonHandler={buttonHandler} counter={0} />
      </div>
    </div>
  );
}

export default App;

Button.js

import React from 'react';

function Button(props) {

  return (
    <div>
      <button onClick={props.buttonHandler}>
          Number of clicks: {props.counter}
      </button>
    </div>
  );
}

export default Button;

0

u/[deleted] May 02 '20

[deleted] — view deleted comment

1

u/[deleted] May 02 '20

Ohhh, you can run code in the root of the component. Ok, that makes more sense then. Thanks!

0

u/[deleted] May 02 '20

[deleted] — view deleted comment

1

u/[deleted] May 02 '20

You don't have to use xs/sm/md/lg/xl in Bootstrap. Try something like

<div class="container">
  <div class="row">
    <div class="col">
      1 of 2
    </div>
    <div class="col">
      2 of 2
    </div>
  </div>
  <div class="row">
    <div class="col">
      1 of 3
    </div>
    <div class="col">
      2 of 3
    </div>
    <div class="col">
      3 of 3
    </div>
  </div>
</div>

This should wrap only when there isn't enough room for the element.

0

u/[deleted] May 02 '20

[deleted] — view deleted comment

1

u/2020-2050_SHTF May 03 '20

I think the “viewport” meta tag is important here — it has direct influence on the pixel type (CSS pixels/resolution pixels).

If we set content="width=device-width" it would use CSS pixels (i. e. “ 375 x 812px” for Iphone 11), without this attribute it will take the actual resolution pixels (i.e. “ 1125 x 2436px” for Iphone 11).

So Bootstrap is still relevant, if you are using CSS pixels on your page/app.

1

u/badboyzpwns May 02 '20

newbie question about redux. If I only wanted to use ComponentDidMount() and call something once. Should I use a class or a react hook?

For example:

const StreamList = (props) => {
    const [streams, setStreams] = useState("");

    useEffect(() => {
        props.fetchStreams();
    }, []);

    return <div>StreamList</div>;
};

vs

class StreamList extends React.Component {
    componentDidMount() {
        this.props.fetchStreams();
    }

    render() {
        return <div>StreamList</div>;
    }
}

I tend not to use setStreams() so it may be redundant. I'm thinking classes are more suitable for this?

0

u/[deleted] May 03 '20

[deleted] — view deleted comment

1

u/badboyzpwns May 03 '20

Oh wow, total brain fart! For some reason, I though that when you want to use useEffect() you also have to initialize value like

const [streams] = useState('")

But useeffect can be ran only once without the code above!! thank you haha

1

u/ortz3 May 02 '20

Is creating a key to render a child component a good design practice. For example I want to send the userId to a child component, but the child component is loading before the userId gets set. This is what I currently have and am wondering if this https://stackoverflow.com/questions/56640380/how-can-i-make-sure-a-react-parent-component-loads-data-before-its-child-compone is good design practice

constructor(){
    super();
    this.state = {
        userId: "" //Set this to "" when deployed
      }
  }

componentDidMount(){
    this.props.user.map((user)=>{
       this.setState({userId: user.User_Id})
    })
} 

render() {    
    return (
        <div>
            <Navbar />
            <CreateRecipeForm userId={this.state.userId}/>  //Called before state gets set
        </div>
    )
}

0

u/[deleted] May 02 '20

[deleted] — view deleted comment

1

u/ortz3 May 03 '20

It's coming from redux so is an object

1

u/eloquenthsn May 02 '20 edited May 02 '20

Hello folks.

So, recently I am trying to find a job and one of them introduced me a challenge that I fetch data store in Redux and display them and make the app capable of search and sort etc.

I hope that it is appropriate to ask something like this... Anyways, I sent the project to them last weekend and I haven't heard anything from them since then. I was just wondering that some of you maybe give some advice and quick review about my code, what could be done to improve. I know that some parts are ugly and repetitive.

For example, following code snippet is the page that is listing some movies(the project is Typescript and NextJS.)

Thanks in advance, really appreciated.

import { useEffect, useReducer, useState } from 'react'
import { NextPage } from 'next'
import { useDispatch, useSelector } from 'react-redux'
import { connect } from 'react-redux'
import ShowGrid from '../../components/ShowGrid'
import { moviesSelector, fetchMovies } from '../../store/movies'
import Layout from '../../components/Layout'
import SearchSortBar from '../../components/SearchSortBar'


const MoviesPage: NextPage = () => {
  const dispatch = useDispatch()
  const { movies, loading, hasErrors } = useSelector(moviesSelector)
  const [searchResults, setSearchResults] = useState([])
  const [userInput, setUserInput] = useReducer(
    (state, newState) => ({ ...state, ...newState }),
    {
      searchTerm: "",
      sortTerm: "",
    }
  );
  const handleChange = event => {
    const { name, value } = event.target;
    setUserInput({ [name]: value });
  };


  useEffect(() => {
    dispatch(fetchMovies())
  }, [dispatch])
  useEffect(() => {
    const filteredData = userInput.searchTerm.length >= 3 ? movies.filter(movie => movie.title.toLowerCase().includes(userInput.searchTerm.toLowerCase())) : movies
    setSearchResults(filteredData)
    if (userInput.sortTerm === 'descendingyear') {
      setSearchResults(filteredData.slice().sort((first, second) => first.releaseYear < second.releaseYear ? 1 : -1))
    } else if (userInput.sortTerm === 'ascendingyear') {
      setSearchResults(filteredData.slice().sort((first, second) => first.releaseYear > second.releaseYear ? 1 : -1))
    } else if (userInput.sortTerm === 'descendingtitle') {
      setSearchResults(filteredData.slice().sort((first, second) => first.title < second.title ? 1 : -1))
    }
    else if (userInput.sortTerm === 'ascendingtitle') {
      setSearchResults(filteredData.slice().sort((first, second) => first.title > second.title ? 1 : -1))
    }
  }, [userInput]);


  return (
    <Layout>
      {loading && <p>Loading...</p>}
      {hasErrors && <p>Error!!</p>}
      <SearchSortBar searchTerm={userInput.searchTerm} sortTerm={userInput.sortTerm} handleChange={handleChange} />
      <ShowGrid entertainmentPieces={searchResults} />
    </Layout>
  );
};
export default connect(state => state)(MoviesPage)

1

u/Eracar May 03 '20 edited May 04 '20

I'm trying to make a scrabble-like game with an infinite board. Are there any libraries or recommendations for how to implement like an infinite coordinate system that you can pan around on and place things on?

I tried doing it myself by rendering everything relative to an origin point and handling panning by having a an offsetX and offsetY which I updated on mouseMove. But it seemed like it wasn't going to be very smooth. Even with just a few points rendered it wasn't very crispy.

I found this thing https://n43.github.io/react-pannable/?path=/story/pad--overview but it isn't exactly what I'm looking for.

Edit: I think I was overcomplicating what I need. The board doesn't have to be infinite. I'm just going to make it kind of big, and then use react-draggable to move it around inside a fixed size parent window.

0

u/[deleted] May 04 '20

[deleted] — view deleted comment

2

u/inter_ception May 04 '20

Create something of your own from scratch first or if you have created something with just JavaScript earlier turn that into react based website, add functionality to it if you can. Following a tutorial is not a test of your skill ability to make things using what you learnt is.

1

u/badboyzpwns May 04 '20

just confirming. In redux-form, ooes the form parameter only serve to clarify to developers on what the form is for? I haven't seen any use of the property yet.

const formWrapped = reduxForm({
    form: "streamCreate",   //is this just for clarificaion?
    validate,
})(StreamCreate);

I've been checking out the Docs but can't seem to find any info on it

1

u/inter_ception May 04 '20

I haven't used this library but from what I am reading the form parameter is used if you want to use the data from the form itself in another component. So say you have a form with input email but you want to also show the value of the email input field in another component while its being typed or after submission. You would access the data by first mentioning which form it is and then which field you want to access in it. In this example it would be email.

1

u/badboyzpwns May 04 '20

Ahh thank you!!! appreciate the help!

1

u/badboyzpwns May 05 '20

I've read that it can be bad for performance when you have deeply nested components and you create an anonymous function in an element. For example,

<button onClick= {() => {callMe("ok")}/> 

Because of the anonymous function, React will re-render every single element in the component because it thinks that the component changed.

How do you guys counter-act this? Does doing

<button onClick={callMe.bind(this, "ok")}/>

a better alternative?

2

u/[deleted] May 05 '20

For the most part, you shouldn't worry about this. It's a micro-optimization. There are rare cases where this causes a noticeable performance impact for the end user, but you could easily go through your web dev career and never run into that issue, depending on the kinds of projects you work on.

So writing extra code to prevent this is only worth it if you've found an actual performance issue, and you have benchmarks in place to make sure that preventing these re-renders is actually improving performance.

1

u/badboyzpwns May 05 '20

Ahh got it! thank you for the heads up!!

0

u/[deleted] May 05 '20

[deleted] — view deleted comment

2

u/badboyzpwns May 05 '20

Thanks!!!!

As in something like this?

> For class components, use a method.

For class:

callMe(response){
    return function b(response){
          return response
    }
}

<button onClick={callMe.bind(this, "ok")}/>

Then for functional components:

const[response, setResponse] = useState(null);

useCallback(() =>{
  setResponse("ok")
}, [setResponse, response]) //I'm not too entirely sure what to put here! 

<button onClick={callMe.bind(this, "ok")}/>

0

u/[deleted] May 05 '20

[deleted] — view deleted comment

2

u/badboyzpwns May 05 '20

Thank you so much for your help! I appreciate it a ton!!! Really made everything super clear now!!!

A last follow up question, I saw a tuortial doing

const handleAlertResponseClick = useCallback(() => {
  alert(response);
}, [setRespone response]) //What's the point of adding setResponse here? 

//Recreate the function when setResponse somehow "changes"? 

//that dosne't make sense

0

u/[deleted] May 05 '20

[deleted] — view deleted comment

1

u/badboyzpwns May 05 '20

Thank you again for the detailed response!!! I think I can relate to this! I usualy do this in order to replicate a componentDidMount

const hey = useEffect(() => {
  setResponse('ok'):
}, []);

But as you said, I get nasty ESLint warnings! It always says "React Hook has missing dependencies: Either include them or remove the dependency array. However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect.eslint(react-hooks/exhaustive-deps) "

From my understanding by putting in the set function inside the array

const hey = useEffect(() => {
  setResponse('ok'):
}, [setResponse]);

It is a way to make ESLint be quiet about it? and that it's not harmful to exclude it? Either approach is fine, but the former approach would cause ESLINT warnings!

0

u/[deleted] May 05 '20

[deleted] — view deleted comment

1

u/badboyzpwns May 06 '20

Awesome! I'll be using it!! thank you so much!!

1

u/BengtJJ May 05 '20

Doing a react web app, have it hosted on Heroku and want to set up a database. Heroku has a postgres free tier.

Was able to set it all up from my "backend" and could manipulate the database.

But this is from where I run the finished prod build of the react app. Not from the development app where I do the actual coding.

How can I set up a database for testing / developing from the frontend/production side of the react app?

1

u/cmaronchick May 06 '20

I am working with the Spotify APIs and authentication and am a bit frustrated by the relatively short expiration time of the access token.

I tried using jwt-decode to check the expiration date/time, but I get an error because the Spotify access token uses _ rather than "." (I think; I get an error anyway whenever I try to decide the Spotify token)

Are there other libraries out there that people like for deciding JWTs?

My other thought is simply to refresh the access token with each Spotify call, but that seems excessive and I worry it wound affect performance.

3

u/thompa89 May 06 '20

Maybe you already know it, but you cant refresh the token from the client. My solution for this is a nodejs server that handles the tokens and each request to the Spotify API. Take a look for inspiration. Its not perfect and under development.

1

u/cmaronchick May 06 '20

u/thompa89, you beautiful bastard. Adding the expiration field is genius in its simplicity. Thank you!

1

u/floghdraki May 06 '20

If I pass function to parent component and call it (without using imperative handle) why can't it access current state of the child component? What is its context? Could someone reference me to the concepts that explain this behavior?

2

u/Awnry_Abe May 06 '20

It should have closed over anything at the time of the function's "instantiation". For an FC, that would be on render. Is the parent holding onto an out-ofdate instance of the function? Got a code snippet?

1

u/floghdraki May 06 '20

Yes that's exactly what happens. Got any reference you could recommend? I put code example to other reply https://www.reddit.com/r/reactjs/comments/gb541i/z/fpp9hit

1

u/Awnry_Abe May 07 '20

I had to learn about it the same way as you--through pain. The concept is called "closure". If you Google "JavaScript closure" you'll get a mountain of resources.

1

u/LeanJavaBean May 06 '20

Hi, I'm trying to create a reusable OHLC chart component, and I'm hoping to use D3FC to do so. For the moment I'm just trying to get this example to render in React, but am struggling to do so. CodeSandbox here. Thanks!

1

u/MeltingDog May 07 '20

I am using Material UI.

I want to custom it's components with values from the Default Theme (https://material-ui.com/customization/default-theme/).

I know I can add these with custom classes like such:

import { makeStyles, Theme } from '@material-ui/styles';

const useStyles = makeStyles((theme: Theme) => ({
  customBadgeStyles: {
    background: theme.palette.primary.main,
  }
}));

But I would rather use withStyles to target specific parts of the component, eg:

import withStyles from '@material-ui/core/styles';

const StyledBadge = withStyles({
  badge: {
    color: theme.palette.common.black,
  },
})(Badge);

But I cannot figure out how to do this.

Would anyone be able to help me out?

1

u/dance2die May 07 '20

Hi u/MeltingDog

Can you post relevant code (Badge) and possibly a runnable sample or a repository for folks to help you out?
(because asking for help for help rarely works in most communities).

1

u/MeltingDog May 07 '20

I'm not sure what you mean sorry. Badge is a Material UI component https://material-ui.com/api/badge/ - I didn't make it.

I'm not sure how to make a runnable sample as I am working on 1 component of a very large project (so can't share repo either sorry).

1

u/089-083 May 07 '20

Guys, how does one go about building a website + platform like this app: Flowalgo.com

0

u/[deleted] May 07 '20

[deleted] — view deleted comment

1

u/089-083 May 07 '20

I actually already started, and have a react app that calls the API and gets data based on text input. But I want to build this correctly and be able to scale.

I want a website where users can pick a subscription and sign up, then log in to the platform through the website. My question is, where should I start? Platform? Website? Front end? Backend?

0

u/[deleted] May 07 '20

[deleted] — view deleted comment

1

u/089-083 May 07 '20

I plan on using the MERN stack. The way I understand it, MongoDB stores data I want to save, Express is the connection between react and the node server, React is the front end, and Node is the server.

So you recommend starting with the website side, where a user can login/sign up and be taken to the rudimentary platform I’ve built so far, and go from there?

1

u/bayhack May 08 '20

I am havng this strange import/export error when packaging a React context as a component: https://stackoverflow.com/questions/61649633/creating-a-npm-module-out-of-a-react-context

I organized the code in the StackOverflow post above with more info.

1

u/Jorick_DC May 08 '20

Hi,

I am trying a fucntion which I declared in a seperate file. When I clikc the button to fire the function nothing heappens can someone explain me what I am doing wrong.

EXAMPLE

Firebase.js

export const doSignOut = () => firebase.auth().signOut();

SignOutPage.js

import  doSignOut  from '../Firebase';

const SignOutButton = () => (
<button type="button" onClick={ () => doSignOut } >
        Sign out
</button>
);

4

u/Nathanfenner May 08 '20

The callback you've passed: () => doSignOut just takes the value of the function doSignOut and discards it.

You want to write

<button type="button" onClick={ () => doSignOut() } >
        Sign out
</button>

or alternatively, pass the function directly as the callback parameter:

<button type="button" onClick={doSignOut} >
        Sign out
</button>

(on Reddit, indent your code 4 spaces to get proper formatting)

1

u/Jorick_DC May 09 '20

Hi Nathan,

Thank you for youre response when i try to pass the function as a callback parameter I get the following error.

Expected `onClick` listener to be a function, instead got a value of `object` type.

I think i messed something up with the export of the function.

1

u/Jorick_DC May 09 '20

O i found out why it didn't work i imported it as a default but needed to import de Sign out function like this import { doSignOut } instead of import doSignOut .

0

u/[deleted] May 08 '20

[deleted] — view deleted comment

1

u/Jorick_DC May 09 '20

Hi Charles,

First of al sorry I gave such a vague description of my problem. Second i was able to solve it I didn't export the function as default function but I imported the function as a default function which is why no api calls were made. When i imported the function as { doSignOut } evrything worked as expected.