Doubt about where to declare variable

Asked

Viewed 37 times

0

I have a query on an object that is in a functional component in React Native. I have created a main matrix (arrayholder) to store all data while filter the information in the status variable (clients).

My question is this, when I declare arrayholder outside the scope of the function it is filled with the data correctly, but when I declare within the scope it simply does not receive the data leaving an empty array. Why? Until then I did not understand very well the difference of declaring variables inside or outside the scope of the functional component.

Follows the code:

import React, { useState, useEffect } from 'react'

let arrayholder = [] - quando declarada aqui fora é alimentada no loadClients

export default props => {
    const [clients, setClients] = useState([])
    const [isLoading, setIsLoading] = useState(false)
    const [search, setSearch] = useState(null)
    //let arrayholder = [] - quando declarada aqui dentro não é alimentada no loadClients

    useEffect(() => loadClients(), [])

    const loadClients = async () => {
        try {
            setIsLoading(true)
            const res = await axios.get(`${serverClients}?auth=${props.token}`)
            setClients(res.data)
            arrayholder = res.data //alimento aqui
            setIsLoading(false)
        } catch (e) {
            showError(e)
        }
    }

    const updateSearch = search => {
        console.warn(arrayholder) //visualizo o conteudo
    }
}
  • If it takes values and you want to keep them in that array, why not create a state for it (const [arrayholder, setArrayholder] = useState(...))? The way you did, declaring out of function, ended up generating a closure.

  • 1

    When you do let arrayholder = [] within the function, it reset the value of arrayholder every re-rendering of the component. If you want to persist the data, create a state to arrayholder.

  • Hi my friend, helping me once again... kkkkkkkkkkkkkkkkk Dude, I didn’t create a state because I just wanted to understand why before. So when I create a variable within the function it resets to each rendering? Why? Do you have any text on the subject? And how did the way I did end up generating a closure? Hugs

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.