Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
React Native, pushing items to an array state not working

I need to push items to my array, but when I console.log this array, it says 'undefined' for the specific value. I'm trying btw to fetch data from firebase storage. How do I correctly add items to an Array

Here is my code:

const [imagelinks, setImagelinks] = React.useState(['']);
const myFunction = () =>{
  await storage()
      .ref(`${_userid}`)
      .list()
      .then(result => {
        result.items.forEach(async ref => {
          await storage()
            .ref(ref.fullPath)
            .getDownloadURL()
            .then(url => {
              //get url
              setImagelinks([...imagelinks, url]);
              console.log('Links: ' + url);
            });
        });
       //there it says undefined when logging...
       console.log(imagelinks[0])
      });
}

Edit: can I use following?

const imagelinks = [];

//instead of 
const [imagelinks, setImagelinks] = useState([]);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Updating state is an asynchronous task. A re-render of the component is required in order to have the updated value. To be sure, add your console outside of myFunction, below the state definition for example:

const [imagelinks, setImagelinks] = React.useState(['']);
console.log(imagelinks)

If you wanna use the result to do some logic (an API call for example), you can use the useEffect hook, like this for example:

useEffect(()=>{

  if(imagelinks.length>0){
    // do your things, except do not call setImagelinks in here to avoid having a loop because imagelinks is in the dependencies  array of useEffect.
  }

},[imagelinks])
about 4 years ago · Juan Pablo Isaza Relatório

0

As the previous answer mentioned, you can't access the new state in the same scope after setting it as it will still have the old value for that specific scope.

If you really need to store and access some value in the same scope you can use useRef hook or you can store the value in a variable in that scope.

Here is an example, but keep in mind that changing the referenced value will not trigger a re-render so this will not replace your useState.

variable example:

let imageLinksArray=[...imagelinks, url] //add this in your function
console.log(imageLinksArray) //you can pass this to the next function

useRef example:

const imagelinksRef = useRef() //add this on top after your useState
...
imageLinksRef.current=[...imagelinks, url] //add this in your function
console.log(imageLinksRef.current) //this will give you the result you're expecting

you can also check out this npm package that let's you access the new state through a ref directly after setting it (if you really need to) https://www.npmjs.com/package/react-usestateref

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda