Home > Back-end >  why i am getting an error while i am using useState as an array
why i am getting an error while i am using useState as an array

Time:05-24

import axios from "axios";
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
  const [userDataInfo, setUserDataInfo] = useState([]);
  const fetchData = () => {
    axios
      .get("https://random-data-api.com/api/address/random_address")
      .then(function (response) {
        // console.log(response.data);
        return JSON.stringify(response);
      })
      .then(function (data) {
        setUserDataInfo(data);
      });
  };
  useEffect(() => {
    fetchData();
  }, [userDataInfo]);
  return (
    <div className="App">
      {userDataInfo.map((data) => (
        <p>{}</p>
      ))}
    </div>
  );
}
TypeError
userDataInfo.map is not a function
App
/src/App.js:26:20
  23 | 
  24 | return (
  25 |   <div className="App">
> 26 |     {userDataInfo.map((data) => (
     |                  ^
  27 |       <p>{}</p>
  28 |     ))}`enter code here`
  29 |   </div>

Generally, the map() method is used to iterate over an array and call a function on every element of the array and if I am using userDataInfo as an array then why I am getting this error?

CodePudding user response:

  const [userDataInfo, setUserDataInfo] = useState([]);

userDataInfo starts out as an array.


  .get("https://random-data-api.com/api/address/random_address")

But then you get that URL which returns a JSON representation of an object (not an array).


  return JSON.stringify(response);

And then you convert the object into a string of JSON before storing that string in setUserDataInfo.


  • Don't convert your data to JSON. JSON is a format useful for sending to external places through APIs (like fetch or localStorage). It isn't useful for processing data structures internally.
  • Do decide what format of data you want to store in userDataInfo. If you are going to store multiple addresses in there, then use an array (and change your handling of the data from the URL to reflect that … e.g. by adding to an existing array instead of overwriting with a single value). If you are going to use only a single item, then only store a single item (and get rid of the map).

CodePudding user response:

response object would be in the following format

{
data:"some data"
}

assuming that the api request returns an array then all you need to do is:

axios
      .get("https://random-data-api.com/api/address/random_address")
      .then(function (response) {
        setUserDataInfo(response.data);
      })

perhaps take a look at the axios documentation if need further clarification on the response schema below:

https://axios-http.com/docs/res_schema

  • Related