简体   繁体   中英

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', …}

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM