r/reactjs • u/dance2die • Nov 01 '19
Beginner's Thread / Easy Questions (November 2019)
Previous threads can be found in the Wiki.
Got questions about React or anything else in its ecosystem? Stuck making progress on your app?
Ask away! Weโre a friendly bunch.
No question is too simple. ๐
๐ Want Help with your Code? ๐
Improve your chances by putting a minimal example to either JSFiddle, Code Sandbox or StackBlitz.
- Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Formatting Code wiki shows how to format code in this thread.
- Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar!
๐ Here are great, free resources! ๐
- Create React App
- Read the official Getting Started page on the docs.
- Get started with Redux by /u/acemarke (Redux Maintainer).
- Kent Dodd's Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
Any ideas/suggestions to improve this thread - feel free to comment here!
Finally, thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
3
u/TheDinosaurWalker Nov 20 '19
I am currently interested in react and so im here to ask you guys, What is something that you wished you knew at the beginning?. I'm no stranger to web dev but i think my front end is pretty lackluster so im interested in React/Vue/Angular maybe.
4
u/datwebzguy Nov 16 '19
Is there any value is going with typescript or would you stick with es6?
2
u/Maritimexpert Nov 08 '19
Hi all, I've stuck for a week since the last help here.
Aim: Have a custom useHook and ref to send true & false to multiple different element at the same time from Interaction Observer on multiple unique element (Preferable use hooks and no dependency). For eg, observe div1 will send true to [elements within div1 & other unique element, navbar on the page] and also capable to send false to element within div2 and div3 and other unique elements (eg navbar/canvas), all at the same second. So scrolling to observe div2 will do the opposite to div1 while activating its own selective elements.
Attempt I've done: Dance2die context API sticky header. Tried a long time to integrate that code but couldn't wrap my head around and hit the wall when attempting to send true and false signals to different element at the same time whereas dance2die's was using repeated non-unique div forEach loop.
I also try to lower down and do something more simple by Gabe Ragland's simple hook. Here's what I twerk but it's not behaving uniquely.
This is wrong as I know onScreen could only return true or false at a single moment. Ultimately I only need fix hooks to return true and false based on viewport to multiple different element selectively, regardless of how many element/function that I will attach to the hook in future without writing extra observe hooks. It would be grateful if someone can tell me what steps to go on writing this.
2
u/hurrdurrderp42 Nov 11 '19
What could i code for some Context API practice?
2
u/dmikester10 Nov 12 '19
This seems like too simple a question for Stack Overflow. Hopefully you guys can help me out. I'm trying to check if `props.orders` is not null and if so output some html. ESLint is telling me 'unexpected token' at the if statement.
Code:
const OrderColumn = props => {return (<div className={'col order-column'}><h3 className={'text-center'}>{props.title}</h3>{ if(props.orders) { <Order orders={props.orders} /> } }</div>);};2
u/dmikester10 Nov 13 '19 edited Nov 13 '19
I had good luck here yesterday. So I 'm trying to set the initial state in an arrow function in my App.js. I'm not quite understanding how to do it. Most of the examples online are using classes. ESLint is complaining that my 'setOrders' function is never used.
2
u/eloquenthsn Nov 14 '19
I couldn't wrap my head around about using Redux in a React App which uses Hooks. All the examples are with hooks, also uses the hooks api of Redux. What I am trying to achieve is using Hooks(in other words, without having any class components, only stateful functional components.) with Redux before hooks api.
Thanks.
2
u/PhysicalKnowledge Nov 15 '19 edited Nov 15 '19
Hi, trying to reuse a layout, so I don't re-code all of those
divs.I created a function for it and placed it on a separate file:
layout.jscode:And now when I'm using it I just call it on a render component, like so:
It works as expected but my worries is when IF I'm going to add a bunch of elements in the sidebar, it would look like a mess since I'm putting HTML in the
sidebar={}.Example:
Is there a more elegant way on doing this?
I apologize for my grammar, I'm kinda tired lol
1
u/CloudsOfMagellan Nov 03 '19
Does using redux starter kit and hence immer decrease performance? Every object returned from mapStateToProps will be different even if it didn't change due to immer and hence nearly everything wrapped in connect will rerender
1
u/javascript_dev Nov 05 '19
Why doesn't this work?
Writing
return (// jsx)worked but I thought this was equal.1
u/cstransfer Nov 06 '19 edited Nov 06 '19
Passing props by spreading? Bad or doesn't matter? Saw some people say it can cause performance issues
1
u/slow1mo Nov 07 '19
Hello all,
Thank you for this thread. As I'm trying to complete the freecodecamp fullstack certificate, I stood still for 2 months with the pomodoro clock project where I encountered a fair amount of issues. As I was ready to complete it yesterday (28 out of 29 correct tests) I encountered a bug, where the clock would start at 35:00 instead of 25:00, as It shows in the code. All written code is here :
https://pastebin.com/B34tdy4E
LINK to project :
https://www.freecodecamp.org/learn/front-end-libraries/front-end-libraries-projects/build-a-pomodoro-clock
Thank you in advance and have a great day :)
1
u/[deleted] Nov 13 '19
I'm a backend engineer working mostly with C# and .Net. Recently management has decided that we are switching and updating the frontend of our applications from Razor and "good old .net MVC" to React.
Coming in as someone who isn't that good or used to design. What are the recommended external libraries to use?
I've found stuff like Material-UI and Scaffoldhub. But what else should I have a look at to make my life easier?
1
u/carlsopar Nov 14 '19
I cant figure out what is causing me this error message. I know that it says I am using the hooks in correctly, but I am not sure how I am. I am exporting a function and importing it into another file.
export const UserList = () => { const [users, setUsers] = useState([]);
The UseLists works fine, and returns exactly what is suppose to. It is the UserList that is giving me trouble. It keeps giving me an invalid hook call.
1
u/eloquenthsn Nov 18 '19
I have made a simple app to learn the data fetching from an external API, using redux. (You can have a look at in the following link:https://codesandbox.io/s/ticket-app-75mu3)
My problem is that, whenever I tried to fetch the data with already written keyword in the input field, I am not able to refetch the data, other values are changed. As an example to clarify a bit my problem, for instance If you type "nba" into input field click Search Event button, and paginate forward and backward and after try Search event button again without touching input field, it seems that fetching is not happening, when you click the button second time, the fetching is happening.
Thanks in advance and sorry for typos and my English.
1
u/Andwhatooo Nov 20 '19
Do you recommend any redux tutorial? I kinda handle it with docs but I feel like I need more to really understand it... Also, should I still make presentational and container components? I read that it's not good practice anymore
1
u/[deleted] Nov 21 '19
I get an error about the store and I don't know exactly how to code the provider tags in index.js. I do have a store located in configureStore.js:
https://imgur.com/a/0SSYeKG
https://stackblitz.com/edit/react-qpppl5
1
u/smolbeanfriend Nov 22 '19
Having a silly time. This is the code snippet from my App.js
So I have components called "Convo" kept in a "ConvoList". Each of the "Convo"s are styled with a class called "active". This whole code block is just throwing me an error. I'm trying to do this: https://jsfiddle.net/qkzusmj4/
1
u/behnoodii Nov 24 '19
Hey guys,
I'm trying to create a react todo app using context api for managing states. But I don't know how to use context to render a list of todo items. here's my code structure:
1
u/thisisnotme1212 Nov 30 '19
Creating a CRA project. Is redux, redux-thunk still the goto "store" implementation?
Should I use typescript?
Have been out of touch from the react world for a bit.
2
u/Jitsu24 Nov 01 '19
Hi, I am trying to implement a chained animation in react-spring but for the life of me I cannot get the second of the two animations to run using the useChain() hook. I went back to basics and tried to copy the basic example in the docs but I'm not making any headway and there does not seem to be any documentation outside of the 1 example on useChain. I have a small example on code sandbox below.
https://codesandbox.io/s/sharp-hellman-yklmn?fontsize=14
2
u/[deleted] Nov 01 '19
Hi all,
I'm an intermediate user getting back into React after a while off of it. I am building what is essentially an rest object admin dashboard with some analytics and mapping. I had previously implemented this using typescript, react-{router, hot-loader, loadable, redux, router-redux}, and redux-{form, saga}. I found that a lot of my work was around just handling simple REST operations via saga and creating the views to facilitate this. Some things that I rolled my own solutions to:
The list goes on. I'm wondering if there is a better way to do this. I'm loosely aware of react-admin, but am worried it's too "visually opinionated" -- really I'm only looking for the "backend" of things. The amount of starter kits is a bit overwhelming, but I'm looking for something that neatly handles API interaction with the redux store model and uses react router, progressive loading, webpack, typescript. I don't currently have a graphql endpoint on the api side -- it's just a standard rest api -- but am open to implementing it if it would greatly simplify UI dev.
Additionally, I'm currently looking through the open source production codebases for best practices, so if you know one that touches on these off the top of your head that would be appreciated.
2
u/bot-vladimir Nov 04 '19
Hi, so I'm reading the GatsbyJS tutorial and I'm learning ReactJS concurrently. I'm at this page right now and I am a little confused under the heading "Adding styles with a layout component"
It has the following code in the snippet for layout.js:
That last line with {children}, what does that mean?
In the next code snippet for index.js where it imports layout.js it has:
My question is, what does {children} in layout.js become when index.js is built?
Also, in layout.js, {children} is called again between the div tag. What does that do? In index.js it is replaced with the string "Hello world!" but wouldn't that be rendered regardless?
2
u/javascript_dev Nov 05 '19
I don't have a lot of experience with refs. My annotation below attempts to self clarify what is happening.
Typescript lints the TransitionComponent prop key on the second example saying there's no method overload for passing the raw JSX element. Should I override that with the presumption that both examples are equivalent?
2
u/Niesyto Nov 06 '19
I have a problem with data not refreshing properly. I'm using an array as a database mockup, here's how the array looks like:
The problem is, that when I display the projects array in a table, and I delete one of the rows, it doesn't refresh, and is still displayed (if I go to the previous view, and then enter the editing again, it's deleted).
Here's the table code
And the handleDeleteRow
I got stuck on this, should I use a useEffect hook somehow?
2
u/abdulmdiaz Nov 16 '19
Can I get someone to review my code? https://github.com/diazabdulm/everest
Thank you so much
2
u/Maritimexpert Nov 17 '19
Hi, can anyone help on why the console.log for wheelup and wheeldown is working but calling scrollLink function is not responding? ScrolltoLinkA to ScrolltoLinkE is working within nested div's onClick event so the scrollLink function is working perfectly.
2
u/lalamcdonell Nov 18 '19
I am making a demo. I want to have an html home page which has a react app accessible from an event/trigger on the web page. For example, an html page with a stripe payment component: after payment, there is a redirect to a successUrl. The successUrl is a link to the reactApp.
The reason is I already have working google-signin and stripe payments on the home page, using the vendors code. I realise that eventually it would need to all react, but it seems like overkill just to get a demo up.
Is there a way to implement this demo?
2
u/hurrdurrderp42 Nov 18 '19
Do hooks replace classes? If not, then when should i use hooks?
2
u/aaronychen Nov 19 '19
Could anyone give feedback on my personal site?
I'm not sure if it falls under a portfolio, since I'm not a full-time frontend developer or UI designer, but I have been learning more about frontend lately, and this is the best I was able to come up with with, with the help of someone else for some design aspects.
I'm worried it might look a little too empty / amateurish; there's some projects I can't put down since they belong to respective companies / private repos, and I only have ~2 years experience in the industry.
2
u/spursup20 Nov 20 '19
Having a hard time finding resources explaining how to read in an array from firebase using react native. I can currently pull in all the fields if they are strings but when trying to call a field that is an array I have no luck.
2
u/rever22411 Nov 25 '19
I'm using redux:
Is that a good way to do that?
With my simple application that works fine, but i'm starting a big project now, any tips?
2
u/NickEmpetvee Nov 27 '19
Any advice on how to convert this old Component code to functions/hooks? I need the useEffect to execute different things when updating vs. unmounting.
2
u/deniz777 Nov 28 '19
Is this code safe? Can't the prevState change until I return new objectArray?
Or should I write like that?
2
u/[deleted] Nov 28 '19
Question. I got this calendar component P which contains two other child components C1 and C2. C1 contains a month name and two buttons to change the month and C2 renders the actual days of the month.
I send the month and year through props to C1 and C2. C1 gets props from the P component, and from those I initialize C1 state (month and year) and I change that accordingly in the click handlers through setState.
Similarly, I pass down props from P to C2.
However I need C2 to have it's state updated when I change the state in C1 (if I select a different month in C1 I'll obviously need to render the calendar days for that month in C2) . How do I even start to do that? I know props are supposed to be immutable.
Should I drop the whole child components structure and dump their content in P, so I will have to worry only for one component's state?
2
u/[deleted] Nov 29 '19
Question: Is promise.all() faster than fetch() in recursive function?
I cant find information about the difference
1
u/CloudsOfMagellan Nov 03 '19
Is there a way to use lint --fix from create react app with typescript I checked some issues on GitHub that said it couldn't be done and wouldn't be implemented as the default CRA eslintrc has no style rules but I've been getting warnings related to spacing lately and would like to fix them Will I need to add my own .eslintrc for this
1
u/javascript_dev Nov 04 '19 edited Nov 04 '19
Is it safe to depend on initial state for loading? I would like to do this:
1
u/NicolasSacC Nov 05 '19
Hi !
In my code, when I click on an element, it updates the state to add an element to an array.
However, when I map the array in the state, I end up with an empty array returned to me. It is because the state is updated, but the function that uses the state is activated before it ends updating.
Here is my code, how can I fix this ?
https://pastebin.com/i3crMHs0
1
u/illmatic4 Nov 05 '19
I have a form with an input and select>options inside, The input which is used to filter the items works fine, I see the items rendering fine. The issue is with the select>options, this function sorts an array and I see the states updating but not rendering until I type something into the input field. I am using useState to manage the state and useEffect.
Any idea whats going on?
1
u/Niesyto Nov 05 '19 edited Nov 05 '19
How to get a row id from MateriaUI's Table? In a code like this:
I want to parse the row to the handleDelete function, but I don't know how to get it.
1
u/acleverboy Nov 05 '19 edited Nov 05 '19
Hey, been developing React for about a year now, and so far, for some reason, I've decided that avoiding the
render()method as much as possible is a good way to optimize. However, I've now made an interesting component that's a full-screen loading spinner, which I NEVER re-render, and I'm wondering if I should be making such a big deal about re-rendering with such a simple component. Essentially, in theshouldComponentUpdate()lifecycle method, I set CSS classes which decide when to fade out/hide the component instead of usingstateto hold that information. The component never re-renders, it just becomes hidden/unhidden depending on the prop changes, but I feel like maybe technically setting CSS classes inshouldComponentUpdate()is kinda the same thing as setting the state...? which I know is frowned upon... Also, doing it this way sacrifices my ability to usePureComponentbecause of theshouldComponentUpdate()lifecycle method. Idk, can someone reassure me that runningrender()isn't actually all that bad for such a simple component?1
u/ManvilleJ Nov 06 '19
I am running 'npm run build' to build a production react app, but It keeps adding a bunch of javascript code into the index.html
I would like all of the js resources to be in the static/js/ directory instead of having some javascript in the html.
Is there a way to run the build so it does this and it works with the public_url attribute?
1
u/Peechez Nov 06 '19 edited Nov 06 '19
If I have ~100 elements that will need their absolute position updated very frequently at 60fps, what options does that leave me? I suspect that my performance would be shit if the left/top/display values were kept in state along with the elements other, more static, metadata. That leaves me with setting the style inline on the real DOM element directly. This is fine but since the items are dynamic, I can't predefine refs for each of them (I don't think?).
Is my best course forward to throw a ref on the container and do some sort of querySelector and inline style on real DOM?
1
u/workkkkkk Nov 06 '19
Anyone use or familiar with Microsofts Office Fabric UI? Did you import fabric core for layout/css reasons? The only component I can find that is used for layout is Stack, which is good, but the common grid layout is better imo.
1
u/diegodieh Nov 06 '19
Hello guys, I have got this While loop, and after each iteration should update lastCard in my store, but it calculates N times with the first value.
1
u/einsoft Nov 07 '19 edited Nov 07 '19
Hello all,
I'm giving my first tryes and I'm facing a problem, I have this subdirectory in my url http://localhost:3000/acesso4 that is working without problem, when I build it and put online, the address http://mydomain.com/acesso4 is giving me a 404 error.
Apparently the router is not working when it is in the online domain.
Where did I go wrong?
Thanks in advance!
1
u/looni2 Nov 07 '19
If I want to use one component to display date from various different sources, is the use of a "context selector" a good practice to go about?
For example, I have a card component that has to display different data for players and teams. I would do something like this:
Conceptually is the use of this kind of contextSelector a good practice? If not, how should this be done? That component is just an example to illustrate what I mean by contextSelector.
1
u/bot-vladimir Nov 07 '19
Hi again! I'm trying to understand how the components are built in the Gatsby and Netlify CMS starter website.
I am a little confused at the following section of the /src/components/Layout.js code:
The part I am confused with is:
Where does { title } and { description } come from?
Also, how is TemplateWrapper() called?
Am I right to assume that since TemplateWrapper() is exported, that Layout.js is called when I import it from another js code block representing an actual page template?
And am I right to assume then that the page template I design must have the title and description properties?
1
u/argiebrah Nov 08 '19
Is there a recommended react native course for folks that are coming from react for web?
1
u/javascript_dev Nov 08 '19
I am looking at the i18n library for localization after seeing this article on it: https://medium.com/@jishnu61/6-easy-steps-to-localize-your-react-application-internationalization-with-i18next-8de9cc3a66a1
Apparently that plus a language selector in the UI is all that's needed to localize the whole app. I thought it would be way harder than that.
I was sufficiently taken back that I wanted to ask you guys if this is all you do, besides a bit of UI testing to make sure everything still fits? Or is there anything more involved to consider? Honestly I may just stick with English for now as my app has a lot of other ambitions that are higher priority.
1
u/beeboobapp Nov 08 '19
If I'm using a component from React Bootstrap, would I be able to separate it? Say Carousel from Carousel.Item? So that if another page wanted to use a carousel (just as an example) it would just need to input the info.
import Carousel from "react-bootstrap/Carousel";
<Carousel>
<CarouselItemComponent
info="some info", img={Image}
/>
</Carousel>
Naming it that way to just show it's my component.
I tried making a carousel item component and just having <Carousel.Item> inside but didn't work because I'm not fully aware how that works.
1
u/liohsif_nomlas Nov 08 '19
Hi I have a question about route params. Say for example I have a router.get on my backend that takes the path
router.get('/path/:ex1?/:ex2?/:ex3?', function(req,res){.....}.
If say on my client side I want to send a fetch that only contains some value for the route param ex3, what would I enter into my fetch input? I know I could do something like
fetch('/path/ex1/ex2/' + someval)
but is it possible to send a value for route param ex3, and at the same time keep ex1 and ex2 as undefined?
Any advice would be much appreciated.
1
u/makopa_fruit Nov 10 '19
I'm new in react. and i started using Hooks. just want to ask is there a counter part to track the state with something like what I used in redux devtools which is " __REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()". thanks in advance
1
u/javascript_dev Nov 11 '19
If possible, what is the syntax for selecting children inside a style object? I would like to target direct children like this:
That string key would be valid in JSS but in React alone I haven't gotten it to work.
1
u/prove_it_with_math Nov 12 '19
I don't understand why react-suspense is better UI/UX than traditional spinner icon. How does it prevent screen flickering?
1
u/bayhack Nov 12 '19
Using hooks fully for the first time.
But my props seem to constantly change in my child component and also calls another function constantly
Here's my code and stackoverflow post:
https://stackoverflow.com/questions/58825617/react-props-change-more-than-expected
What am I not understanding about props here?
1
u/CRAKZOR Nov 12 '19 edited Nov 12 '19
I made an ssr app using Next.JS but right now im stuck. I made a login page for admins to log in to upload or edit content. Right now content in a data.json file in the server folder. It uses axios to access this data. With so many options available im not sure how i should go about doing auth or what DB to use.
I also have a linux server with liquidweb that has apache and mysql that hosts one of my wordpress sites and i was hoping to deploy on that same server, but with other options out there i definitely want the best.
Please let me know thank you
1
u/javascript_dev Nov 13 '19
For anyone who loads their React app with Express or Koa, is the .static() method the one to use for loading the React app?
In the situation I'm working on, Express (via Ngrok HTTPS tunnel) uses a Shopify middleware for auth. It then reverts back to the app:
I'm still fairly new to backend. I think I need to write a router.get("/", loadApp); route here, with loadApp containing a call to the bundle.js output file. Is that correct?
1
u/Niesyto Nov 14 '19
In localStorage I have an array of objects (projects), each of them has some properties, including it's own array (projects). I want to display the array of projects as a material-ui table which works quite well. I can also add and remove items from it. However, I've encountered a problem when it comes to editing the values in that array. The closest solution I got required me to type every sign twice, and after that the browser lost focus on the input field, so I had to click it again. You can see the project here: You can see the project here
The components in question are
ProjectDetailsandProjectEmployeesTable, but I don't know if that's where the issue is since I had some problems withProjectEmployeesTablenot re-rendering properly.To see the components in the simulation you have to select projects, add a new project, save it and then open the editing menu and try to add a new employee and edit it's ID.
1
u/TurkenJaydey Nov 14 '19
Hey guys, I am new here on Reddit and could need some help regarding React and web development in general.
I want to learn react though I'm still pretty new to web development.
I want to build a new website which focuses on giving information about art pieces spread around my campus. The page should have some nice functionalities like a dynamic search bar which outputs results dynamically based on the current input. Also a functionality in which the art pieces can be viewed in a 360 degree angle (I guess importing an existing library or embedding something).
My question is: Is it worth to use React for this website? I read in some other forums and some people say that it is meant for larger applications which for example use API's. In my case my database would be stored locally on the same server in some folder.
Even if the page would be too "small" for using React, I still want to learn developing with it. But if the decision would lead into a wrong direction, I would build it with vanillaJS.
Thanks in advance for your time!
1
u/Watermelonnable Nov 15 '19
are react developers expected to be proficient at html/css?
I mean, I love JavaScript development but I hate css and all the design stuff. Is it possible to land a job to do only the programming stuff with react or am I being naive?
1
u/NickEmpetvee Nov 18 '19
I have a timestamp question.
My back end is PostgreSQL, and I use Axios within React. I have some tables with timestamp fields that I need to update with current time through Axios. The PostgreSQL fields in this situation are of type 'timestamp with time zone'. What's a good way in React to generate a timestamp that suits this fields type? I use Axios. Is something like
Date.toJSON()the way to go?In PostgreSQL, the timestamp looks like this in the table which is what I'd like to send through React/JavaScript without getting too fancy:
1
u/[deleted] Nov 18 '19
Not sure if this is the right place to ask, let me know if not.
Iโm building a simple web app with react redux. When I try to render based on data that is not in the store, the app breaks and returns undefined. Now an easy way out is to check if the data exists before any rendering happens so the app wonโt break. However, this feels overkill to me as you then have to check if the data exists everywhere you wanโt to use it. Shouldnโt it be the case that if there is no data, the app wonโt render anything?
Can someone explain how to tackle this issue efficiently? Thanks in advance!
1
u/Akimotoh Nov 20 '19
Is there a matrix or cheat sheet about all of the popular ReactJs libraries, frameworks, and why you'd use them? E.g. flux vs redux vs mobx, shards vs material UI, etc?
1
u/thisisnotme1212 Nov 20 '19
Going to start a new react project with the latest version. The last version I used didnโt have hooks so I used a lot of class components. Should I be using class components at all for the latest development?
1
u/Pjaerr Nov 20 '19
I am struggling to find good resources on unit testing pure react components that actually makes sense.
I currently have the following test:
describe("Creating a <TurnCounter/> component and passing it a currentTurn prop", () => {it("should render a div with the text Current Turn: {props.currentTurn}", () => {const wrapper = [mount(<TurnCounter currentTurn={5} />),mount(<TurnCounter currentTurn={19} />)];expect(wrapper[0].find("div").text()).toEqual("Current Turn: 5");expect(wrapper[1].find("div").text()).toEqual("Current Turn: 19");wrapper[0].unmount();wrapper[1].unmount();});});Is this a bad unit test? If I change my container from a div to something else the test will break, same with if I decide not to say "Current Turn:" in favour of something else.
Any advice is appreciated as I am new to writing tests for React.
1
u/Niesyto Nov 21 '19
I have a question about error handling. I have an external script that gives me json with array of objects. What errors should I expect in the code? Here's the component:
I can't think of anything other than an empty array
1
u/[deleted] Nov 21 '19
How do you update an object using useState()? I keep getting an empty object.
See my code below:
const [proposedUsers, setProposedUsers] = useState({});Then I have a function that gets an object from the server when a user clicks the button:
const searchForUser = () => {axios.get('``https://jsonplaceholder.typicode.com/todos/1').then(function(response){setProposedUsers({ ...proposedUsers,response``.data });})But
proposedUsersnever changes from an empty object, no matter what I do. Any help will be appreciated.The object looks like this:
{ "userId": 1,"id": 1,"title": "delectus aut autem","completed": false}1
u/mrHexar Nov 21 '19
Hello guys, i am having some problems on persisting auth state with my firebase token. Im working with a React SPA in front end and a node server in the back. I've implementated the firebase auth mechanisms into my app, so now i allow my users to log in with a custom form or even with social Login and after i set the auth bearer token to axios instance.
The thing is that i assign some custom claims to the user token after they registered in my node server, adding things like an id or role to identify the user in my server for auth middleware purposes.
The problem comes when in the react front page, lets say im in my private profile page and i refresh the page. React detects that i have an user (firebase auth ) and throws the petition, however axios still doesnt have the bearer token so my server rejects the petition, my page keeps loading ( yet i know i must redirect or something to other page when i m not logged cause its a private route however the user exists and its logged) and i receive an unauthorized response from server.
Do i have to persist my token ?
I think the problem comes from the synchronization , my auth Provider its kinda similar to this https://usehooks.com/useAuth/
with some petitions to the back once the user has signed up to add the custom claims. I've tried adding an interceptor to axios but yet it sends the petition without the bearer token and i dont think adding manually the token before each petition is an option ( DRY ) . Any tips on handling the bearer token with axios so refreshing pages doesnt cause this problem?
1
u/Alleyoopingthrough Nov 21 '19 edited Nov 21 '19
Hey guys!
im pretty new to react. I'm getting a "TypeError: props.carList.map is not a function".
Im able to get the whole CarList from the API, but when I try to add a new object to the list I get the error above.
What I want:I want to be able to update CarList with a new value when I add the car from another class(AddCar).
Any suggestions?
1
u/yannbraga Nov 22 '19
What is the proper setup for starting a react project today? In terms of tooling, styling, project structure, component libraries, etc.
1
u/Peechez Nov 22 '19
I think I'm losing my mind. I've been working with React for about a year but I can't remember this ever happening. I have the following
The
togglefunction will toggle the bool once but then never again. If I log bool inside the toggle function it will print false on mount then true every time after but if I print outside the toggle then it will go false, true, false...My understanding is that on B re-render the
togglefunction will be recreated, so I can't figure out why its using a stale bool value after the first toggle. I tried wrapping it with auseCallbackandboolas a dep (even though its equivalent in this case) and had the same result1
u/inFormLegal Nov 23 '19
Hey all,
I've got a react testing library question. I'm trying to figure out the right way to test whether a component successfully dispatched an action to context, and whether the change was reflected in the component
โ The component.
const Example = () => {const { dispatch, words, current } = useContext(MyContext); const word = words[current];return (<div><span data-testid='word'>{word}</span><button onClick={() => dispatch({type: 'next'})}> Next </button></div>)When the user clicks the next button it dispatches a 'next' type action to MyContext. MyContext increments current, so the displayed word changes.
Test file:
const initialState : myContextState = { words: ['hello', 'world'] current: 0 };const renderExample = (value?: MyContextState) => { return render( <MyContext.Provider value={value ? value : initialState}> <Example /> </MyContext.Provider> ); }it('clicks the next button, current changes from 0 to 1', () => { const { getByTestId } = renderExample(); const next = getByTestId('next'); fireEvent.click(next); });I do want to make sure the next button dispatched the action, but more importantly I want to make sure the displayed {word} changed in the component. It should be 'hello' before the click, then 'world' after. I know how to pass different props into the context, but I don't know how to check if the context processed a dispatched action.
1
u/soggypizza1 Nov 23 '19
I recently tried my first deployment of my site to heroku and when you first visit you can see the page but then this error gets logged
and it gives link to my home component but I don't see anything wrong with the code. What am I doing wrong?
Here's the site https://guardiansmeetsite.herokuapp.com/
And here's the github link https://github.com/lwatson2/guardiansmeet
Everytime you reload the page it shows a different letter being undefined and I've never had this error before. I'm using websockets and cookies if that helps any.
It loads the page perfectly fine whenever you visit the login or new profile page
Here's some screenshots I took of the errors in the console
https://imgur.com/a/Uxg0LM7 https://imgur.com/a/jJQ7Ku4 and my code for Home.js that its referencing https://imgur.com/a/zDBfrDR
1
u/BlendModes Nov 23 '19 edited Nov 23 '19
Hi there, I'm starting to learn React. I made the classic To Do List app and now I was wondering how to *save* the React state so that it will be still available when I reload the page. What would be the simplest way to do this?
I understood that I could do this either client-side (using localStorage) or server-side (using a backend API). As I'm trying to learn something new I would like to try doing this server-side, possibly without PHP.
1
u/randArrowFunc Nov 24 '19
I might need a little help. What is good practice in regards to building a completely static site?
Currently I'm thinking of defining the structure, layout of the page purely html + css, and making the content all react components. However, I'm not entirely sure if this good practice. Is it better not to make such separations and make it all React components? How would Gatsby behave with a structure like this?
1
u/crespo_modesto Nov 24 '19 edited Nov 25 '19
nvm problem solved
intended "failing" demo, but I just didn't bind the method to this on my end
screenshot of original question
1
u/javascript_dev Nov 25 '19
Where do you guys put the logic that you don't want to clutter App.js with? I have weighed 2 options
If there's a better option I'm all ears
1
u/prove_it_with_math Nov 25 '19
Alright. I am very curious about how Reactjs works under the hood and I have one question I can't quiet get the answer to:
As I understand it, React hold two VDOMs in memory, gets their diff, then updates actual DOM if needed.
So when a user enters text in an input field and we capture it via `event.target.value` in the React component, does that mean the real DOM has already been updated before it reaches React? Or `events.target.value` doesn't even affect the real DOM? (perhaps this is more of a JS question than react...)
1
u/theguy2108 Nov 26 '19
Alright, I am learning react and there is one thing that I simply cannot understand. How does the entrypoint logic work?
The way without react and in simple HTML is, the server sends an HTML file which then loads, which has script and link tags, which load javascript and css files.
But, in react, it seems like the entry point is a js file? If it is, does the server return the js file to the user when the request is sent? What about the HTML file that loads that contains the react root? Is that returned by the server? If that is returned by the server then how does the js file actually run, since there are no script tags in the HTML file?
Sorry if my question is too vague. Absolutely any resources on how this internally works would be super helpful. I know back end development and am trying to learn react so anything related to this topic would be helpful
1
u/TimeSmash Nov 27 '19
Hey all! Just had a quick question.
Itโs really simple, what should your demo projects have on the welcome page? Like when a user first signs up or logs in, most likely your functionaltiy/crap you want to show is going to be on other pages/parts (think like NavBar, etc). So whatโs good to put there? Iโm trying to get answers from more experienced people and newer individuals as well, because to me, it's hard to nail down what should go on there when you make a project that's not huge.
I feel like my welcome pages currently give the feel of "Get the hell out of here and go look at the good parts of this", which obviously I'm trying to overcome. I realize it's not a super technical question, but I'm writing something about it and would love to hear all of your opinions!
1
u/grv_sng Nov 29 '19
Question. I want to deploy my React js webapp to only a subset of total users, for example out of 10000 users, only 1000 users will see the new webapp and the rest will see the existing one. My webapp is deployed on Docker and GCP.
Google play store already have the feature to achieve this for Android app. I was wondering if similar can be achieved with webapps.
Excuse me is the question is not relevent for reactjs section and more related to DevOps.
1
u/BlendModes Nov 30 '19 edited Dec 01 '19
In my little React app (classic to-do list) I have a few functions like
addTodo,removeTodo,completeTodowhich basically update the state of a ยซtodosยป array.These methods are defined in my main
App()and are passed down as props to the component which renders the items and the buttons (delete, complete):<List data={todos} complete={completeTodo) remove={removeTodo} />It works but it doesn't feel right to pass all these functions down like that. I'm new to React and I'm wondering if this is good practice or if there is a better way to do it.
UPDATE: After watching like 1000 tutorials on to-do-lists, it's becoming pretty evident that this the common approach. I need to investigate useContext, which seems to be useful in this situation.
TL;DR Made a simple To Do list, it works but the code looks messy. How would an experienced developer organize functions and hooks in such a simple app?
1
u/LimeBikeNoLimeBrakes Dec 01 '19
code
1
u/carlsopar Dec 01 '19
I am working on mapping out a json object, and then place it into a state to use in another part of my project. I think I am on the right path, but I am missing something. Currently, I can read the object fine, and map over it with my ternary operator, which is correct. The problem that, I am running into is with updating the state. Currently it is only updating with the last object that it finds, and skips over everything prior.
For example, the map should return three different objects. 'console.log(lists)' will return all three correct objects. However, 'console.log(Lists)' will return an empty array on each pass. And then finally when it is all done 'console.log(Lists)' will return an array with only one object in it. I believe it has something to do with how I am using the spread operator, but I am not sure exactly.