1

I'm fetching data in React using axios like the following :

Hooks

const [date, setdate] = React.useState([]);

useEffect(() => {
  axios
    .get("http://localhost:8000/api/profilevisit/all/" + params.id)
    .then((response) => {
      setdate(response.data.data);       

      let NewArray = date.map((item, index) => {
        return <span>{item.date}</span>;
      });
      console.log(NewArray);
 
    })
    .catch((err) => console.log(err));
}, []);

console.log(response.data.data):

(2) [{…}, {…}]
0: {date: "2021-05-15", views: 15}
1: {date: "2021-05-16", views: 6}
length: 2
__proto__: Array(0)

I would want to retrive from that array only date elements so I will have an array like this :

[2021-05-15, 2021-05-16]

I think I'm close but I can't put my finger on what's wrong as I created a loop in NewArray to get item.date but the NewArray in console doesn't returns anything. Any ideas ?

Edit : API direct response

{
    "data": [
        {
            "date": "2021-05-15",
            "views": 15
        },
        {
            "date": "2021-05-16",
            "views": 5
        }
    ]
}
AlyaKra
  • 486
  • 8
  • 22

3 Answers3

3

You can loop through the array and insert into another array. For example,

let dates = [];
response.data.data.forEach(item => {
    dates.push(item.date);
});
console.log(dates); // array
Ravi Kiran
  • 565
  • 1
  • 8
  • 22
1

This should work. You're setting a state and accessing it immediately which won't really work as its async. First set up a temp array. Then push the date item onto the temp array. Finally when all is said and done, set the state i.e setDate with that temp array. The dates would now be accesible in the desired format.

const [date, setdate] = React.useState([]);

useEffect(() => {
  let tempArr = [];
  axios
    .get("http://localhost:8000/api/profilevisit/all/" + params.id)
    .then((response) => {    
      response.data.data.forEach(item=>{
        tempArr.push(item.date);
      })
 
    })
    .catch((err) => console.log(err));
    setDate(tempArr)
}, []);
Hadi Pawar
  • 1,090
  • 1
  • 11
  • 23
  • 1
    unnecessary to reassign to a new variabel -> redundant code, you can just do this within the response and on catch do nothing. If this fails setDate will be overwritten with empty tempArr, but maybe this should only be changed on success – lehm.ro May 16 '21 at 10:29
0

if you want to get only elements that match a certain criteria use .filter()

myarray.filter(element => "add any logic here that returns true to keep element or false to remove it") in the end myarray will only have elements that match your criteria

for example with element needing to be older than 25

myarray = [{ name: 'max', age: 27 }, { name: 'paul', age: 25 }]

myarray.filter(element => element.age > 25) 


myarray will be: [{ name: 'max', age: 27 }]
lehm.ro
  • 750
  • 4
  • 16