r/learnreactjs • • Apr 01 '23

One state handler calls another state handler... they do not update together

2 Upvotes

handleVotes calls handleMostVoted, handleMostVoted reads the votes array one render too late. I know this is an asynchronous problem but I cannot seem to get them to sync up. Any advice here? Code included.

const App = () => {
  const anecdotes = [
'If it hurts, do it more often.',
'Adding manpower to a late software project makes it later!',
'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
'Premature optimization is the root of all evil.',
'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.',
'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients.',
'The only way to go fast, is to go well.'
  ]

  const [selected, setSelected] = useState(0)
  const [votes, setVotes] = useState(Array(anecdotes.length).fill(0))
  const [mostVoted, setMostVoted] = useState(-1)
  const handleSelected = () => {
  const randomSelect = Math.floor(Math.random() * anecdotes.length)
setSelected(randomSelect)
  }

  const handleVotes = () => {
    const copy = [...votes]
copy[selected] +=1
setVotes(copy)
handleMostVoted()
  }
  const handleMostVoted = () => {
console.log(...votes)
    const winner = votes.indexOf(Math.max(...votes))
setMostVoted(winner)
  }
  return (
<div>
<div>
<h1>Selected Anecdote</h1>
{anecdotes[selected]}
<p>This anecdote has {votes[selected]} votes</p>
</div>
<div>
<Button text='next anecdote' clickHandler={handleSelected}/>
<Button text='vote' clickHandler={handleVotes} handleMostVoted={handleMostVoted}/>
</div>
<div>
<h1>Most Voted Anecdote</h1>
<Voted mostVoted={mostVoted} anecdotes={anecdotes}/>
</div>
</div>
  )
}


r/learnreactjs • • Mar 30 '23

How to Create and Validate Forms With React Hook Form

Thumbnail
catalins.tech
3 Upvotes

r/learnreactjs • • Mar 30 '23

Is anyone out there who's started learning react recently? I need help.

2 Upvotes

So i started learning react a few weeks ago but i've been facing quite a lot of challenges and i feel learning with someone who's also starting out is going to be easier. So if there's anyone out here who's willing to do that with me please reach out i'll be delighted if you do.
I would also love being mentored by someone who has experience with react so you can also reach out to me thank you all


r/learnreactjs • • Mar 29 '23

Resource Too many useState? Let's useReducer!

Thumbnail
time2hack.com
1 Upvotes

r/learnreactjs • • Mar 27 '23

Ready, Set, Deploy: The Ultimate Guide to Preparing Your App for Launch!

Thumbnail
youtube.com
5 Upvotes

r/learnreactjs • • Mar 27 '23

How to Create a Stunning Portfolio Website with Nextjs, Tailwind CSS and Framer-motion🌟 [Demo: https://minimal-nextjs-portfolio-website.vercel.app/]

Thumbnail
youtu.be
5 Upvotes

r/learnreactjs • • Mar 27 '23

Resource Managing Forms with React Hook Form

Thumbnail
claritydev.net
0 Upvotes

r/learnreactjs • • Mar 27 '23

Resource Free Review Copies of "React.js — Key Concepts" Book. for unbiased reviews

0 Upvotes

Packt has published "React.js — Key Concepts". The book is written by our Star Author - Maximilian Schwarzmuller.

As part of our marketing activities, we are offering free digital copies of the book in return for unbiased and honest feedback in the form of a reader review on Amazon

Here’s what’s included in the book:

1.Build modern, user-friendly, and reactive web apps

2.Create components and utilize props to pass data between them

3.Handle events, perform state updates, and manage conditional content

4.Apply styles dynamically and conditionally to create a modern UI

5Use advanced state management techniques such as React’s context API

6Utilize React router to render different pages for different URLs

7.Understand key best practices and optimization opportunities

If you feel you might be interested in this opportunity, please comment below or can connect with me on Linked In

https://www.linkedin.com/in/royluis-rodrigues-66479123/

(You can connect with me on LinkedIn too however this is not compulsory.)

Thanks and Regards
Royluis Rodrigues

DevRel Marketing Executive @ Packt Publishing


r/learnreactjs • • Mar 27 '23

Question After user sign-up/login, how can I set up a profile for each user? Name, Email, Phone, etc...

0 Upvotes

I have my the sign-up and login set up on Firebase Authentication (Email and Password). Once a user has signed up, what can I use to store user profile information?

I was looking at Firebase Databases but their docs don't really explain anything or show an example on how to actually use it.

Is there better option you would recommend?.


r/learnreactjs • • Mar 26 '23

Want to know if I am good enough to land my first job as a front end developer.

3 Upvotes

Hi everyone, I've been learning front-end development for the past 10 months and I'm wondering if I'm ready to land my first job as a junior front-end developer. I have proficiency with HTML, CSS, JavaScript, and React and I've been working on some projects to showcase my skills.

I'm hoping to get some feedback on my projects and advice on what I can do to improve my skills and increase my chances of getting hired. I'm also curious to hear from people who have landed their first job as a front-end developer and what their experience was like.

Here are a few of my projects that I've been working on:

I'd love to hear your thoughts on these projects and any advice you have for me as I look to break into the front-end development industry. Thanks for your help!


r/learnreactjs • • Mar 25 '23

Question Best way to pass arguments into an onclick function

1 Upvotes

Hey all, sorry if this is a dumb question but I'm wondering what's the best way to pass arguments into an onclick function.

E.g.

const func = (a,b,c) => { console.log(a,b,c); };

I know you can use an inline arrow function but I've heard that's not great cause it'll create the function on each render. Like such: <button onClick={() => func(x,y,z)}> Button </button>

I also know that you can use the bind function but idk if that's a good approach.
Like such: <button onClick={func.bind(null, x, y, z)}> Button </button>

Are there any other ways we can use to pass arguments into an onclick function?
Thanks in advance


r/learnreactjs • • Mar 25 '23

Question Trying to create a carousel with reactjs and css, using css transform.

1 Upvotes

Hello everyone I have been trying to create a carousel using reactjs, I am almost done, I am not able create the exact curve effect with css., I have explained the the problem here:

javascript - How to get this curve effect using css with reactjs? - Stack Overflow


r/learnreactjs • • Mar 24 '23

Question how to write an image to the uploads folder

0 Upvotes

Hi guys, Im stuck when it comes to uploading an image to a folder using react.

This is the front end file (dashboard.jsx):

const [file, setFile] = useState(null);

function handleFileChange(event) { setFile(event.target.files[0]); }

const handleImageFileChange = async (event) => { 
    event.preventDefault();
    const formData = new FormData(); formData.append('image', file);
    await axios.post('/upload', formData); 
};

<div>
  <input type="file" onChange={handleFileChange} />
  <button onClick={handleImageFileChange}>Upload</button>
</div>

and this is the backend code:

const upload = multer({ dest: 'upload/' });
    app.post('/upload', upload.single('image'), (req, res) => { 
    res.send('File uploaded successfully!'); 
});

For some reason im getting a 404 that the uploads folder is not found. this is the structure

Public Folder: public/upload

SRC folder: src /components/functionals/dashboard.jsx


r/learnreactjs • • Mar 23 '23

Resource Simplifying code with Maps in JavaScript and React

Thumbnail
claritydev.net
2 Upvotes

r/learnreactjs • • Mar 23 '23

Resource CORS Error: What it is and How to Solve it

Thumbnail
youtube.com
1 Upvotes

r/learnreactjs • • Mar 22 '23

Creating a Developer Website with Indepdnent React Components

Thumbnail
medium.com
1 Upvotes

r/learnreactjs • • Mar 22 '23

I wrote a beginner-friendly blog post on how to use useEffects with setInterval

Thumbnail
self.reactjs
4 Upvotes

r/learnreactjs • • Mar 22 '23

Question How to create numeric pagination with siblings and/or dots using ReactJS?

4 Upvotes

I have data returning a pagination object from the backend as shown below:

{
  "pagination":
    {
      "current": 1,
      "totalpages": 6,
      "pages": [
        1,
        2,
        3,
        4,
        5,
        6
      ],
      "next": {
        "page": 3,
        "limit": 1
      },
      "prev": {
        "page": 1,
        "limit": 1
      }
  }
}

This is because the URL consists of two parameters page=2&limit=1. I currently have 6 objects in my database which is fine, however when it comes to the front-end. I'm unable to figure out how to create the siblings. My pagination literally shows 6 links.

https://i.stack.imgur.com/PcQB1.png

I would like to create something like this, perhaps?

https://i.stack.imgur.com/BGQ8N.png

My current code looks like this:

{
  pagesArrayInfo.pages.map((p, index) => (
    <li
      key={p}
      id={p}
      className={`page-item number-item page-${pagesArrayInfo.pages[index]} ${
        pagesArrayInfo.pages[index] === pageParams.page ? 'active' : ''
      }`}
    >
      <Link
        href={{
          pathname: pagePath,
          query: { page: p, limit: pageParams.limit },
        }}
        className={`page-link`}
      >
        {p}
      </Link>
    </li>
  ))
}

Do you guys have any idea?


r/learnreactjs • • Mar 21 '23

Resource Thinking in React - The Ultimate Beginners Guide

Thumbnail
youtu.be
2 Upvotes

r/learnreactjs • • Mar 20 '23

noob question

2 Upvotes

Hi, so im currently doing a full stack bootcamp, did a month of basic javascript, im comfortable 70-80% with it as im coming from a field with no experience in coding. Next week we are starting to learn react, googled around and most people say you dont need to know js in order to learn react, my question is, is that true ? is react like a total new language ? can i do same things there as in js ? shall I go all in on react or go again over js basics ? Thank you !


r/learnreactjs • • Mar 20 '23

Resource Optimize Redux Development: Simplify Boilerplate Creation with Code Generators and Plop.js

Thumbnail
claritydev.net
2 Upvotes

r/learnreactjs • • Mar 17 '23

Resource Speed up your React developer workflow with Plop.js code generators

Thumbnail
claritydev.net
3 Upvotes

r/learnreactjs • • Mar 15 '23

Question What should I learn next ?

4 Upvotes

I have finished learning most intermediate React concepts and gotten kinda comfortable with React . I've also learned Redux and made a few small / medium sized projects.

I have 2 options now :

  1. Learn Nextjs and Typescript with React
  2. Go the backend route and learn Mongo, Express, Node etc and learn NextJs and Typescript after that.

I also have to land a good internship next year of college as a part of the curriculum. So i have about 6 - 7 months to learn / practice .

What is the better plan of action? Any insights or suggestions are welcome.


r/learnreactjs • • Mar 13 '23

How can I push an object into an array of array in react trough reducer?

3 Upvotes

I am super new to react so I'm completely confused as to what's going on.

I am trying to add "question" and "answer" as an object to a certain array based on the option value selected.
Option value works, as well as payload from inputs, but I can't seem to get the logic of the return with state here:

return [
          ...state,
          htmlArray.push({
            question: action.payload.question,
            answer: action.payload.answer,
          }),
        ];

it just adds number 1 to the state, as another element in state array. I know I should separate my components, but I'm new to all of this, so it's easier for now to think of it in just one file.

Here's the code with removed other cases for transparency :

import React, { useReducer, useState } from "react";
import { v4 as uuidv4 } from "uuid";

const Form = () => {
    
  const [question, setQuestion] = useState("");
  const [answer, setAnswer] = useState("");
  const [option, setOption] = useState("html");

  let htmlArray = [];
  let cssArray = [];
  let jsArray = [];
  let reactArray = [];
  let theoryArray = [];

  const questionReducer = (state, action) => {
    switch (action.type) {
      case "html":
        return [
          ...state,
          htmlArray.push({
            question: action.payload.question,
            answer: action.payload.answer,
          }),
        ];
      default:
        break;
    }
  };

  const [state, dispatch] = useReducer(questionReducer, [
    htmlArray,
    cssArray,
    jsArray,
    reactArray,
    theoryArray,
  ]);
  console.log(state);

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch({
      type: option,
      payload: {
        question: question,
        answer: answer,
      },
    });
    setQuestion("");
    setAnswer("");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        placeholder="question"
        onChange={(e) => setQuestion(e.target.value)}
        value={question}
      />
      <input
        placeholder="answer"
        onChange={(e) => setAnswer(e.target.value)}
        value={answer}
      />
      <select value={option} onChange={(e) => setOption(e.target.value)}>
        <option value="html">HTML</option>
        <option value="css">CSS</option>
        <option value="js">JS</option>
        <option value="react">React</option>
        <option value="theory">CS</option>
      </select>
      <button type="submit" value="Add question">
        Enter Question
      </button>
      <div>{question}</div>
      <div>{answer}</div>
    </form>
  );
};
export default Form;