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

123
Visualizações
How to push multiple json (response ) in single array?

i need data in this form [{..},{..},{..}]. i create blank array const arr = [] and all json data push in this Array. arr.push(data) the output is [{..}] [{..}] but i need all object in one array. how to fix it?

  // const arr = []
  const [data, setData] = useState()
  // const [arrData, setArrData] = useState()
  useEffect(() => {
  const data = JSON.parse(localStorage.getItem('Cart'));
  if (!data) {
    console.log('go to empty Cart')
  } else {
    data.map(async (v) => {
      try {
        axios.get(`/cart/${v}`)
        .then(res=>setData(res.data))
        .catch(e=>{console.log(e)})
      } catch (e) {
        console.log(e);
        navigator('/Login');
      }
    })
  }    
  }, [])
  // arr.push(data)
  console.log(data)

Output

{_id: '61ed1af4ac1a79e2c4f45937', title: 'Birthday bannner Template Tranding Template', DiscountPrice: 149, OriginalPrice: 199, category: 'Birthday Banner', …}


{_id: '61ec1b25689c12b75aa2929a', title: 'Birthday Banner Marathi Template', DiscountPrice: 149, OriginalPrice: 200, category: 'Birthday Banner', …}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Hi @Shreyash Kolhe you can try something like this.

const [data, setData] = useState([]);

with useState you will have the data and a setter function to set data. In your Axios call, you can set the data as below.

setData(preData => [...preData, res.data]);

The preData will hold the previous data which you current state data. This will append the new data with the old data you have in your state. Please share the code next time it will help the community to help you out more effectively.

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use the spread operator to push objects to an array. Refer to the sample code

import React, { useState } from 'react';
import './style.css';

const App = () => {
  const [data, setData] = useState([]);
  const [count, setCount] = useState(1);

  const handleClick = () => {
    // your response from the API call
    const dataObj = {
      id: count,
      name: 'some name',
      title: 'some title',
    };
    setCount((prevCount) => prevCount + 1);
    setData([...data, dataObj]); // should work fine with your implementation as well
  };
  return (
    <div>
      <button onClick={handleClick}>Click to add</button>
      {data.map((item) => (
        <div key={item.id}>
          {item.id} {item.name}
        </div>
      ))}
    </div>
  );
};
export default App;
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