0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.