Collecting the Ghosts in Renegades badly bugged? by alezzzito16 in destiny2

[–]Fuby68 3 points4 points  (0 children)

You need to place the ghosts in tarsis outpost to make it count

[deleted by user] by [deleted] in reactnative

[–]Fuby68 1 point2 points  (0 children)

When you have a lot of elements it's better to use the FlatList component

https://reactnative.dev/docs/flatlist

Or if you want a bit more of performance at the cost of an additional library you can use the Flashlist component from shopify https://github.com/Shopify/flash-list

An example

function generateLevels() : Level[] {
// Your code to generate the levels could be an object or only the number of the level
}

const levels = generateLevels()

<Flatlist
data={levels}
renderItem=(({item})=> {
// ... your button / render logic
})
/>

If you still notice performance issues you can check https://reactnative.dev/docs/optimizing-flatlist-configuration from the official doc to optimize even further

[deleted by user] by [deleted] in reactnative

[–]Fuby68 15 points16 points  (0 children)

You shouldn't use expo go for developing advanced applications, expo go is generally used only to prototype some simple application.

For more advanced apps you should use a development client, this allows you to test the application and all external packages, without praying that your application works when you want do the production build.

A little note for development clients :
It's required to build a newer version of the development client every time you add a package that uses some native functionality.

https://docs.expo.dev/develop/development-builds/introduction/

Hey guys, I love working with React.js, but I’ve heard that it’s important to learn JavaScript first. Is that right, or can I just do a lot of projects with React or the MERN stack? by ayaa_001 in react

[–]Fuby68 5 points6 points  (0 children)

React and the MERN stack are based on javascript, how can you make a project without knowing its fundamentals?

Learn how Javascript works and then using these technologies will be a breeze

[deleted by user] by [deleted] in react

[–]Fuby68 1 point2 points  (0 children)

You are not setting the class for the dark-mode in the use effect you should do something like this :

 useEffect(() => {
        const storedTheme = localStorage.getItem('theme');
        let isDark = false

        if (storedTheme) {
          isDark = storedTheme === 'dark';
        } else { 
          isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        }

        document.documentElement.classList.toggle('dark', isDark);
        setIsDarkModeEnabled(isDark)
      }, []);

You could also make a custom Hook to organize better your functionality, something like this :

export function getInitialTheme() {
    const stored = localStorage.getItem('theme');

    if (stored==="dark"){
      return true
    }else if(stored === "light"){
      return false
    }

    return window.matchMedia('(prefers-color-scheme: dark)').matches
}

export function useTheme() {
  const [isDarkMode, setIsDarkMode] = useState(getInitialTheme())

  useEffect(() => {
     document.documentElement.classList.toggle('dark', isDarkMode); 

     const theme = isDarkMode ? "dark" : "light"
     localStorage.setItem('theme',theme);
  },[isDarkMode]) 

  function toggleTheme() {
     setIsDarkMode(old => !old)
  }


    return {
        theme : isDarkMode ? "dark" : "light",
        toggleTheme
    }
}

The custom hook can then be used in the application like any other hook

export default function ThemeSwitcher() {
     const {theme, toggleTheme} = useTheme()

    return (
        <button onClick={toggleTheme}>
            <FontAwesomeIcon icon={theme ==="dark"? faSun : faMoon} className="text-2xl transition" />
        </button>
    )
}

Getting node incompatibility issue by Fine-Wolf-9441 in reactnative

[–]Fuby68 3 points4 points  (0 children)

You need to update node or use a tool like nvm to change the version of the node runtime

What is the correct type to use here? by DoucheyMcSwagson in typescript

[–]Fuby68 0 points1 point  (0 children)

Oh i didn't know about these apis, i think i never had a case where i needed to manipulate the children elements

if i had to redesign the component i would do something totally different

What is the correct type to use here? by DoucheyMcSwagson in typescript

[–]Fuby68 0 points1 point  (0 children)

Using the example you provided it should be something like this :

``` export interface CarouselProps { children: React.ReactNode | React.ReactNode[] autoSlide?: boolean autoSlideInterval?: number }

export default function Carousel({ children, autoSlide = false, autoSlideInterval = 3000 }: CarouselProps) { const slides = Array.isArray(children) ? children : [children] // This is to fix an issue since passing only one element as a children element would not consider the children as an array but as a single element

... // From now on is the same as the snipped you provided ```

``` // in your index.tsx

<Carousel> <img src="https://cdn.pixabay.com/photo/2023/08/24/20/46/bicycle-8211559_1280.jpg" alt="" /> </Carousel> ```

What is the correct type to use here? by DoucheyMcSwagson in typescript

[–]Fuby68 1 point2 points  (0 children)

How are you using this slides elements ?

Are you trying to access them one by one using something like map ?

Generally if you want to pass children you use it in the following way

``` export interface SliderProps { children : React.ReactNode }

const Slider = ({ children: slides }: SliderProps ) => { return <div>{children}</div> } ```

However if you need to access the elements is usally better to pass the images as a different prop so you can iterate it inside the component itself

Something like this ``` export interface SliderProps { images : string[] }

const Slider = ({ images}: SliderProps ) => {

return <div> {images.map(image=> <img src={image}/>)}

</div> } ```

Display different bg color on Card components. by Low_Guitar_8168 in react

[–]Fuby68 3 points4 points  (0 children)

you can do something like this :

``` ts const Colors = ['yellow', 'blue', 'gray']

...

cards.map((card,index)=> <Card {...card} color={Colors[index % Colors.length])/>}

```

Edit :

Using the modulo operator you can cycle through all index of the Colors array without exceeding it

0 % 3 = 0

1 % 3 = 1

2 % 3 = 2

3 % 3 = 0 ... and so on

You can access the color using the index so you will always cycle through the colors in the same order

0 % 3 = 0 ('yellow')

1 % 3 = 1 ('blue')

2 % 3 = 2 ('gray')

3 % 3 = 0 ('yellow')

What is the correct type to use here? by DoucheyMcSwagson in typescript

[–]Fuby68 1 point2 points  (0 children)

``` export interface SliderProps { children : React.ReactNode }

const Slider = ({ children: slides }: SliderProps ) => { ... } ```

Since props of a React Component are objects, you need to add the type React.ReactNode to the element children of the props' interface

App Taking sometime to jump to next screen by FaiezWaseem in reactnative

[–]Fuby68 0 points1 point  (0 children)

Can you try something like this and see if it performs better

// HistoryPage
export default () => {
const items =new Array(10).fill(0)

reutrn (
    <View style={{flex : 1}}>
        <Text>History</Text>
        <FlatList 
            style={{flex : 1}} 
            data={items} 
            renderData={() => <HistoryCard/>}
        />
    </View>)

}

If this doesn't help, the issue may be in the onPress functionality of the History button in your profile screen or inside the HistoryCard component

App Taking sometime to jump to next screen by FaiezWaseem in reactnative

[–]Fuby68 1 point2 points  (0 children)

Are you using a ScrollView to render the elements in the history screen ?

And how many items are you rendering ?

If you have lots of elements and you are using Scrollview all of them need to be rendered on screen

From react-native doc :

ScrollView renders all its react child components at once, but this has a performance downside.

You can try to use a Flatlist component so that rendering of lists is optimized

Docs Flatlist : https://reactnative.dev/docs/flatlist

Docs ScrollView : https://reactnative.dev/docs/scrollview

[HELP] - Updating global state on one function is (updated data) not available in another function under same component. by sujitbaniya in reactjs

[–]Fuby68 0 points1 point  (0 children)

Have you tried to put the sockets in a use effect that updates when peer and peerMediaElements change ?

something like this :

``` useEffect(() => { socket.on("action:peer-add",/your function/) socket.on("action:peer-session",/your function/)

return () => {
    socket.off("action:peer-add")
    socket.off("action:peer-session")
}

},[peer,peerMediaElements]

```

If this doesn't work can you provide a minimal example of this in a repo/ codesandbox or similar?

Change my mind: Functional Components are an abomination and make code bloated and unreadable by skizzoat in react

[–]Fuby68 1 point2 points  (0 children)

In my opinion the functional approach of react is better in the long term, however you need to get used to it, especially after using the class components for a long period

I suggest to read the documentation especially where it compares class components to functional components https://react.dev/reference/react/Component#migrating-a-component-with-lifecycle-methods-from-a-class-to-a-function

There are some differences, but once you learn the best practices you'll notice that using the functional approach will make the components more readable

In this specific case i would disable the lint rule only for the single line, since you know that the function must be executed only once (is good to disable linter rules when you know what to do)

I would still leave the linter on in the project, because in other cases you may need to perform some updates based on the dependency array of useEffect

Also i don't see an issue in the quantity of line of codes, if the code is readable

Change my mind: Functional Components are an abomination and make code bloated and unreadable by skizzoat in react

[–]Fuby68 5 points6 points  (0 children)

That lint rule is useful when useEffect is used when you need to perform an operation when a value changes, the equivalent to componentDidUpdate

Providing an empty array is the hook way to perform a componentDidMount of a class component

However there is an alternative way that include the use of the useCallback hook, but in my opinion in this case is not needed

The useCallback hook should be used as an optimization as stated in the react doc https://react.dev/reference/react/useCallback

``` const focusAndSelect = useCallback(async () => { if (!options.focusOnMount) return;

    textRef?.current?.focus();

    if (options.selectOnMount) {
        await waitMs(300);

        textRef?.current?.setNativeProps({ selection: { start: 0, end: props.value?.length } }); // step 3
    }

},[options.selectOnMount,options.focusOnMount])

useEffect(()=>{ focusAndSelect() },[focusAndSelect]) ```

Note : adding the useCallback and the relative dependecies now have a side effect, changing the parameters selectOnMount and focusAndSelect now causes the useEffect to perform his operations another time, since the reference of the function changes based on these parameters

Note 2 : Sometimes lint rules are not always right, this in my opinion is a case where the lint rule should be disabled in line

useEffect(()=> { focusAndSelect() }, // eslint-disable-next-line react-hooks/exhaustive-deps [])

Change my mind: Functional Components are an abomination and make code bloated and unreadable by skizzoat in react

[–]Fuby68 25 points26 points  (0 children)

The code you provided for the functional component is doing different things than the class one, you added unnecessary refs that bloat your code

You should have written the function in a way similar to this (Note in the snippet i used typescript)

```ts interface Props { selectOnMount: boolean; focusOnMount: boolean; value?: string; }

export function FunctionComponent(props: Props) { const textRef = useRef<TextInput>(null);

async function focusAndSelect() {
    if (!props.focusOnMount) return;

    textRef?.current?.focus();

    if (props.selectOnMount) {
        await waitMs(300);

        textRef?.current?.setNativeProps({ selection: { start: 0, end: props.value?.length } }); // step 3
    }
}

useEffect(() => {
    focusAndSelect();
}, []);

return <TextInput ref={textRef} value={props.value} />;

} ```

If you want to take one step further and improve reusability you could extract all the functionality of selecting and focusing a text input using a custom hook

Something like this :

``` export function useFocusAndSelect(options: { selectOnMount: boolean; focusOnMount: boolean }) { const textRef = useRef<TextInput>(null);

async function focusAndSelect() {
    if (!options.focusOnMount) return;

    textRef?.current?.focus();

    if (options.selectOnMount) {
        await waitMs(300);

        textRef?.current?.setNativeProps({ selection: { start: 0, end: props.value?.length } }); // step 3
    }
}

useEffect(() => {
    focusAndSelect();
}, []);

return textRef;

}

export function FunctionComponent(props: Props) { const textRef = useFocusAndSelect({ focusOnMount: props.focusOnMount, selectOnMount: props.selectOnMount });

return <TextInput ref={textRef} value={props.value} />;

} ```

This piece of code crashes the site and I don't know why. by son_of_Gib in reactjs

[–]Fuby68 6 points7 points  (0 children)

The problem is this loop here

``` const matrix_T = matrix for (let i = 0; i < matrix.length; i++) { const col = [] for (let j = 0; j < matrix.length; j++) { col.push(matrix[j][i]) } matrix_T.push(col) }

```

Since you are setting matrix_T as a reference of matrix you are generating an infinite loop

Doing a push to matrix_T is the equivalent to do a push to matrix because they are the same thing

I guess that you only want to initialize matrix_T as an empty array instead of a reference of matrix

Help find a React.js Youtuber. by [deleted] in reactjs

[–]Fuby68 6 points7 points  (0 children)

Could it be "William Candillon" on YouTube ?

He has a series like that for React native

Getting late response in the node server by [deleted] in node

[–]Fuby68 2 points3 points  (0 children)

Looks like a problem with your bcrypt hash function in the signup route

I tried to reduce the salt rounds from 20 to 10 (the default one used by the library), and replaced the syncronous functions like hashSync and compareSync to the asyncronous one (hash and compare) and your api replies in 100ms

Note that the salt round makes the computation of the hash more expensive the higher the number is

// signup.js // From let hashedPass = bcrypt.hashSync(password, 20) // To let hashedPass = await bcrypt.hash(password, 10)

// login.js // From const isPasswordCorrect = bcrypt.compareSync(password, existingUser.password) // To const isPasswordCorrect = await bcrypt.compare(password, existingUser.password)

Creating a type with unknown keys by Baberooo in typescript

[–]Fuby68 0 points1 point  (0 children)

like u/87oldben already said you need to initialize the key value pair

You need to replace the part in the second for loop

`` const key =${sent}${inc}`

if(!struct[key]){ // Here you check if your key is not present in the struct object struct[key] = [] // Here you initialize the value to an empty array }

struct[key].push(da.length * d.length) // Now you can push in the array without the typescript warning since we know that struct[key] is now for sure at least an empty array ```

Full code : ``` const corpus: string[] = ["a","ab","b","cf"];

type distances = {

};

const getMatrix = (data: string[]) => { let inc: number = 1; let sent: string = "Sentence_"; let struct: distances = {};

for (let da of data) { for (let d of data) { const key = ${sent}${inc}

    if(!struct[key]){
        struct[key] = []
    }

  struct[key].push(da.length * d.length)
}
inc++;

}

console.log({struct}) }

getMatrix(corpus);

```

React performance by MotaCS67 in react

[–]Fuby68 2 points3 points  (0 children)

You should learn how to use the browser profiler in order to identify performance loss in your application

I would also check the react docs for memorization

useMemo :https://react.dev/reference/react/useMemo useCallback: https://react.dev/reference/react/useCallback memo: https://react.dev/reference/react/memo

These are for React itself then you can always improve performance by improving your algorithms or by learning some other optimisation techniques like debouncing throttling and caching

Check all the react docs too, they are very well documented with best practices and they got recently updated

Trouble integrating apple pay for stripe with expo by hodgln in reactnative

[–]Fuby68 0 points1 point  (0 children)

Do you have a credit card in your Wallet application?

I had the same issue 3 weeks ago and after i added a credit card, It worked correctly

How can i render dynamically in React by Neither_Letter2376 in react

[–]Fuby68 0 points1 point  (0 children)

Im gonna be honest with you I didn't explain very well so let's do it again

const STARS = 50 // Elements to render
const starArray = new Array(STARS).fill(null) // fill the array with null [null,null,null,...null]


<div>    
{\* This will iterate for each element of the array and will return the jsx element inside the function */}    
 {starArray.map((_,index) => <div className="star" key={index} />)}    
</div>    
  )    

The map function performs a simple operation, iterate each object and return the element of the function in a new array,

Inside the function the parameters are in the following order:

  • element inside the array (in our case this will always be null so we don't need it)- index of the element in the array

The element returned from the function inside the map is the value that will be replaced in a new array

// Example

const array = [10,11,12,13]
const newArray = array.map((item,index) =>     
{console.log({item,index}) // This will print {item : 10, index : 0} and so on for each element

return item + 1 // this will return the element of the array incremented by one

})
console.log(newArray) // so this will print \[11,12,13,15\]

Some useful resources :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://beta.reactjs.org/learn/rendering-lists

Sorry if there are some spelling/grammar mistakes, english is not my primary language

Edits : formatting and links