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

151
Visualizações
How to save and display data retrieved from database

So I've retrieved data in JSON format using GET request then I'm facing a problem in saving into my state so that I can display them into my span/div/h1 using map function. Here's how my JSON data looks like:

[
   {
        "projectName": "SHIBA INU",
        "projectToken": "SHIB",
        "tokenPrice": 0.2,
        "saleStart":{
            "$date": "2021-12-20T20:00:00.00Z"
        },
   {
        "projectName": "BITCOIN",
        "projectToken": "BTC",
        "tokenPrice": 200,
        "saleStart":{
            "$date": "2021-12-20T20:00:00.00Z"
   }
]

So I'm trying to do this way but I dont think it will work:

const [projectData, setProjectData] = useState({})
useEffect(() => {
      axios.get(`my api`).then(res => {
        for(let i=0; i<res.data.length; i+1){
          setProjectData(...projectData, res.data[i])
        }
      }).catch(e => console.log("error: ", e));
    },[]);

I'm not sure whether I should save them into an array or an object

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I agree with @iLuvLogix comment: from the info in your example, it seems like you're trying to store an array of objects, so you'll want to initialize your state with an array, and then add the items from the response to the array as well. You also don't need the loop: you can spread all of the array items into a new array along with the existing state in one step:

const [projectData, setProjectData] = useState([]);

useEffect(() => {
  axios.get(`my api`).then(res => {
    setProjectData([...projectData, ...res.data]);
  }).catch(e => console.log("error: ", e));
}, []);
about 4 years ago · Juan Pablo Isaza Relatório

0

First of all you are not updating your i value in your for loop. Since your i value never will be less than res.data.length, it will loop infinitely. Instead you should use i++ to increment it at each iteration:

for(let i=0; i<res.data.length; i++)

Other than that setting your state like that is problematic. setState in React is async which means when you use it and access your projectData it won't promise you that you are getting the updated state right away. Instead you should try to update your state at once in your case. Also check Why is setState in reactjs Async instead of Sync?

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