TypeError: data.map is not a function in react and django

40 views Asked by At

I'm using Axios to retrieve data from the backend. When I log the data to the console, it appears as an object. However, I need the data to be in an array format. When I try to use the map function on the data, it gives me an error stating that data.map is not a function. I am using django in backend

function Search() {
  const [data,setData] = useState([]) // setting data as array i had also used null here
  useEffect(()=>{
    axios.get("http://127.0.0.1:8000/api/listing") //using axios api
    .then(response =>{
      setData(response.data)
      console.log(response.data) //data is appears as object when do console.log
    })
    .catch(error =>{
      console.log("Error fetching data:",error)
    });
  },[]);
  return (
    <div>
      <h1>Fetched Data</h1>
      {/* <ul>
//data.map is not a function
        {data.map(item =>(
          <li key={item.id}>{item.title}</li>
        ))}
      </ul> */}
    </div>
  )
}

export default Search

I have checked wheather data from backend is in form of array or object and i got that the data is not in form of array

if (Array.isArray(response.data)) {
          setData(response.data);
        } else {
          console.error('Data is not an array:', response.data);
        }

after that i tried to convert data to array in two ways

.then((response) => {
//if data is not in array convert it into array 
        const dataArray = Array.isArray(response.data) ? response.data : [response.data];
        setData(dataArray);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });

another way

<ul>
        {[data].map((item) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>

but both way i got a warning

Each child in a list should have a unique "key" prop. this error i get when i try to convert data to array

1

There are 1 answers

0
usernotavalible On

I got the problem solved here is my console.log output

 results :  Array(2) 0 :  {title: 'The basics of Marketing', author: 2,
 is_published: true, slug: 'marketing'} 1 :  {title: 'The CIA traid',
 author: 1, is_published: true, slug: 'cia-traid'}

I have an object that has a property called result which is an array therefore we have to do something like this we have to access the result array with the data object and then map over it to display the items

Here is how to do this

 <ul>
         {data.result.map((item) => (
           <li key={item.id}>{item.title}</li>
         ))}
 </ul>