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
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.
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?
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.
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.
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?
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?
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.
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.
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:
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?
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.
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]}
`
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?
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)
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.
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.
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.
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?
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
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?
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.
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.
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.
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.
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.
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.
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.
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
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.
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!
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?
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.
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
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.
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.
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.
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
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.
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
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.
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.
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).
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
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 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:
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 POSThttp://localhost:8000/upload/image404 (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);
}
},
}
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.
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.
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.
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.
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.
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*asReactfrom"react";import{useTable}from"react-table";constborderStyle={border:"1px dashed navy"};exportdefaultfunctionApp(){constdata=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"}]}],[]);constcolumns=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
returnrow.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:
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:
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.
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.
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.
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.)
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.
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.
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.
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
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.
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.
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")}/>
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
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
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!
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.
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.
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?
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?
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.
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!
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).
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?
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?
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.
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 .
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.
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,
0
u/[deleted] May 10 '20
[deleted] — view deleted comment
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:
importing useField into the app to be used as follows:
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
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/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:
Functional component
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. :)
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
this.props.game is a reference to my new Game() in my App.js, which I have here:
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?
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/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:
Edited for clarity.
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 :).
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
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/ytdl-node May 09 '20
If I am using React hooks, let's say for a state change, I'd normally write something like:
Now if I pass the
setUsernameandsetAgefunctions to a component let's say 'A' in the following fashion:And in my component 'A', I update the username and the age.
This will cause the main App to re-render twice right? Is it not better if I just use an
objectfor the state? E.G.:Why do we not use this instead?
0
u/[deleted] May 12 '20
[deleted] — view deleted comment
2
u/badboyzpwns May 12 '20 edited May 12 '20
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?
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/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?
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/[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.
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/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-thunkto 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-persistare 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.
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)?
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
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:
And, the app.js file
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
POSThttp://localhost:8000/upload/image404(Not Found) as a result of theawait 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 404at createError (createError.js:16)at settle (settle.js:17)at XMLHttpRequest.handleLoad (xhr.js:61)Any ideas?
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:
What I'm about to use:
I'm not used to decide the schema of the DB myself.
How does it sound to you ?
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
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 -
I did this. After importing a component
I get this error
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/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?
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:
It currently looks like:
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:
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
Button.js
0
u/[deleted] May 02 '20
[deleted] — view deleted comment
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:
vs
I tend not to use setStreams() so it may be redundant. I'm thinking classes are more suitable for this?
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
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.
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
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.
I've been checking out the Docs but can't seem to find any info on it
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,
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
a better alternative?
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.
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?
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:
But I would rather use
withStylesto target specific parts of the component, eg:But I cannot figure out how to do this.
Would anyone be able to help me out?
1
u/089-083 May 07 '20
Guys, how does one go about building a website + platform like this app: Flowalgo.com
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>
);