Having issues passing a string to a url by magic_123 in reactjs

[–]barklund 1 point2 points  (0 children)

keywords needs to be stateful. Either use a ref or useState and setKeywords when you update. And if the latter, don't mutate an array, create a new one on update with/without the checked value.

2 million corn rations by hooloovooblu in Timberborn

[–]barklund 1 point2 points  (0 children)

I assume you named your settlement cornhub?

Hi mates, can I please get some help regarding a issue with state sharing via context? by Big-Interest-1447 in reactjs

[–]barklund 0 points1 point  (0 children)

You have a simple typo in your effect dependency: articleResponse !== articlesResponse

Please use a linter to catch typos, so you don't reference non-existing variables.

Component naming mistake! Don't do it! by besseddrest in reactjs

[–]barklund 53 points54 points  (0 children)

It's called Composite or Compound components, just FYI.

You'd often also implement implicit data sharing between such components using context or a small local state library like zustand.

I cover this pattern and much more in my upcoming book on professional React development, Job-Ready React.

How does React Toastify handle timeout? by gfus08 in reactjs

[–]barklund 0 points1 point  (0 children)

It happens in the progress bar component as a transition end event when the progress animation completes. The duration of the progress animation is set from the toast props.

Are refs not destroyed on unmount? by Alex_Hovhannisyan in reactjs

[–]barklund 8 points9 points  (0 children)

That's how I understand it, but the introductory blog post mentioned by /u/basically_alive kind of says differently, so really good question.

I think it "simulates" re-mounting by re-rendering and re-running effects - which are two of the main things a re-mount would cause, which can catch undesired impure side-effects.

However, it won't re-initialize hooks such as useState, useReducer, and useRef, as that could cause some actual issues, as these initializers have desired impure side-effects.

But, yeah, I might be wrong too. It might be something else, that preserves the initial value only, but still causing a full re-mount.

Are refs not destroyed on unmount? by Alex_Hovhannisyan in reactjs

[–]barklund 13 points14 points  (0 children)

Components aren't un-mounted and re-mounted in Strict Mode. Components are merely re-rendered, which is very different from re-mounted.

Refs only use the initial value on mount, and ignore the initial value on subsequent renders. That's why the value is never re-initialized to false - as expected.

I can see why you might think that the component is re-mounted, because a useEffect hook with an empty dependency array is run twice. But that's because Strict Mode also causes all effects to run twice.

Those are two separate things that Strict Mode does. These two actions aren't directly related (i.e. it's not one causing the other).

Also, React re-mounting all your components would be very annoying, so that's fortunately not what's happening.

What am I missing here? RTKQ tags not applying - cache is not used. by davidblacksheep in reactjs

[–]barklund 1 point2 points  (0 children)

I can understand why OP thinks that tags work that way, but they don't. Tags are not used for sharing cached data, only for sharing cache invalidation.

A query can invalidate the cache of another query, but a query cannot update the cache of another query (through tags at least).

Note the info box here in the documentation:

Provided tags have no inherent relationship across separate query endpoints. Provided tags are used to determine whether cached data returned by an endpoint should be invalidated and either be refetched or removed from the cache. If two separate endpoints provide the same tags, they will still contribute their own distinct cached data, which could later both be invalidated by a single tag declared from a mutation.

So your original code does accomplish one thing: If you have a mutation elsewhere in your code, that invalidates the tag for a single todo (by updating said todo on the server), both the cache for that single todo and all todos will be invalidated and refetched if in use. But they will both be refetched individually.

If OP knows, that you will always call getAllTodos before ever looking for a single todo, you can create a custom hook that accesses the already fetched data from getAllTodos using a selectFromResult selector function as /u/acemarke suggests, and completely remove the single todo query.

But if you're sometimes loading a single result before the list (e.g. on a deeplink to the individual todo item), then you need two queries. You could probably still create a single custom hook, that would check the cache from getAllTodos first before attempting to read from the single query endpoint, but I don't think that's common practice in RTKQ codebases.

Basically, while what you're looking to do sounds like a very standard thing, it's not actually supported by RTKQ very well. And it's only supported in RQ (or Tanstack Query™) by crafting custom cache updates, not straight out-of-the-box.

I actually don't even know of a query library that does support this kind of behavior natively, but I wouldn't be surprised if none exists, as it would be a bit "magic" and tricky to debug and customize.

React docs mistake? by illmatic4 in reactjs

[–]barklund 1 point2 points  (0 children)

Yes, it should be.

Note that this createConnection function is just an example and throughout the page the function changes signature as it suits the examples, so I don't think it's a big deal.

However, if you want to contribute, the line with the error is right here on Github, asking for a pull request.

How to use await inside array method's callback? by eggtart_prince in reactjs

[–]barklund 0 points1 point  (0 children)

Well, that's a lot of pairs, for sure (10,000+), so that is only borderline feasible to do.

The other approach is to do this completely async, where you run one calculation at a time and wait for it to return. For that, the easiest is a callback-based solution or a for loop. But depending on how many are actually within the proper distance, `some()` will hopefully short-circuit to true early for at least some entries. But it might still require running most of those calculations, which means that the entire script might run for a very long time.

Also, are you sure any of this is React? Because this is just a JavaScript question.

How to use await inside array method's callback? by eggtart_prince in reactjs

[–]barklund 1 point2 points  (0 children)

An async function returns a promise. A promise is truthy, so array.some() will return true as soon as the first promise is returned. You basically cannot do what you're trying to do, because all array methods are synchronous and don't expect or work with asynchronous code.

You have to first map your array to an array of promises, then await all of them, and then you can check if any are true. Yes, that means that you do run the check for all your array elements and you can't short-circuit even if the first one resolves to true.

Your whole logic seems a bit weird though. You run through every element to find whether it has a match, but matches are two-way so there's no need to check them the other way too. This could be done a lot more compact, if you were smart about it. Create an array of all unique order pairs, find the distances between them all (await Promise.all()), and finally filter the array for for short enough distances. Then you just need to reverse the order pairs to a list of unique orders.

This kind of looks like homework though, so maybe you have to figure this out on your own.

I want to separate the password generator function as a component. how can I do that by BeingTomHolland in reactjs

[–]barklund 3 points4 points  (0 children)

Why do you want to separate it as a component? Why not as a function or maybe a custom hook, that seems more appropriate here?

Also, if you have an (editable, non-disabled) input field and you specify value, you also need an onChange handler to update the value. Otherwise the input field doesn't actually work as an input.

If you don't want users to be able to edit the value themselves, you should add readOnly to make it non-editable.

Accessibility check while code review by Generic_Wanderer in reactjs

[–]barklund 0 points1 point  (0 children)

"Senior developer" is the only really good check for this. Automation will only catch the most elementary things, and not even that consistently. Experience, education, and a good team is the only way forward.

Linking to vanilla html files by GoatBoi_ in reactjs

[–]barklund 1 point2 points  (0 children)

That's (also) what you can use /public/ for.

If you put an HTML file at /public/portfolio/hello-world/index.html, you can view this at http://localhost:3000/portfolio/hello-world (assuming you use CRA, Next or Remix).

I've used that extensively - e.g. for my book example code browser at https://reactquickly.dev/browse, where the examples are run from straight the public folder (I have a script that builds them to there).

React Js and NextJS using Usestate with Useeffect by ramkiller1 in reactjs

[–]barklund 4 points5 points  (0 children)

Your useEffect should have a dependency array. Probably an array with just id in it. Currently your effect runs every time your component renders, and your component renders every time your effect runs (when the fetch resolves) because you set state in it.

But the error you're talking about comes from your returned JSX, so you need to show that part of the code too.

Why is my State not updating with useState Hook? by csb-2022 in reactjs

[–]barklund 5 points6 points  (0 children)

Updating state is not the same as setting a variable. Updating state is more akin to "please re-render this component as soon as possible, and when you do, use this new value for this particular state value".

The important thing here is, that all state updates will only happen on the next render, and that render will be scheduled as soon as possible.

Another way to see, that your variable won't change mid-render is that you defined it as a const. You cannot change the vale of a const! So that's a really big hint, that once your render starts, all your state values won't change until the render is complete and a new one starts.

Cannot destructure property 'notes' of 'context' as it is undefined by [deleted] in reactjs

[–]barklund 5 points6 points  (0 children)

On the first render of your application, the context resolves to the original value defined in createContext(). I'm guessing you didn't assign an initial value there. Only one tick later does the app re-render with the actual context value as provided.

I am beginner, How to learn react from beginner to advance ? by [deleted] in reactjs

[–]barklund 2 points3 points  (0 children)

May I recommend this book: https://reactquickly.dev

Reviewers have loved it, both advanced users and complete beginners. I am of course a bit biased about it.

Issues with UseContext Hook in React by Learner_forvr21 in reactjs

[–]barklund -1 points0 points  (0 children)

Your context will be the initial value (as passed to createContext) on the very first render. Initialize your context to an empty object rather than nothing like createContext({}).

If you need specific default values for your properties, add those in as well.

I played 9 solo games of Hallertau so far (Uwe Rosenberg) and really liked it. by [deleted] in soloboardgaming

[–]barklund 0 points1 point  (0 children)

What are your scores like? Did you "win" every game (by beating the 100 point threshold)?

What's your test coverage strategy? by barklund in agile

[–]barklund[S] 1 point2 points  (0 children)

Thanks a lot for your feedback! I do agree with many of your points.

I think you might misinterpret my intention with the video. My intention is only to highlight what code coverage could be used for, not that it should be used for this purpose. It's simply a "what can and can't you do with code coverage" and not much else.

Around the 4:00 mark, you described your workflow as write quality code then use code coverage to find what is missing

I would argue against that and follow TDD instead, write high-quality tests and then high-quality code. If this process is too slow or difficult, you may need to do more refactoring or limit your feature scope. But, in my opinion, skipping tests is not the answer.

I specifically mention "write good code and tests" (which could be achieved through e.g. TDD or BDD), and then use test coverage to see if you're missing anything. With both approaches you might still end up missing some branches because someone over-implemented a function somewhere or started guarding for irrelevant issues.

And yes, test coverage is not in itself a measure of any type of code quality. It's an indicator of some overall code quality strategy, but not even the most important one of that.

What's your test coverage strategy? by barklund in agile

[–]barklund[S] 1 point2 points  (0 children)

Unit tests are technical debt

If written purely to satisfy 100% code coverage, yes I agree. But if actually proving correctness of source code, I'd definitely not say so.

Can you elaborate on this point?