zenzone
zenzone

Reputation: 85

How to store data from Axios response?

I'm trying to store axios response but approach 1 seems to be the only one that works.

Approach 1: works ok from state

const [loadingData, setLoadingData] = useState(true);
const [data, setData] = useState([]);

  useEffect(() => {
    async function getData() {
      await axios
        .get("sampleApi")
        .then((response) => {
          setData(response.data);
          setLoadingData(false);
        });
    }
    if (loadingData) {
          getData();
        }
      }, []);

    ...

// This works fine from state
          {data.map(
              (i, index) => {
                return <p key={index}>{i.id}</p>
          }
        )}

Approach 2: Attempting setting as a regular variable instead of state

const [loadingData, setLoadingData] = useState(true);
  let data;


  useEffect(() => {
    async function getData() {
      await axios
        .get("sampleApi")
        .then((response) => {
          data = response.data // <====== This 
          setLoadingData(false);
        });
    }
    if (loadingData) {
          getData();
        }
      }, []);

    ...

// Following results in: Uncaught TypeError: Cannot read properties of undefined (reading 'map')
          {data.map(
              (i, index) => {
                return <p key={index}>{i.id}</p>
          }
        )}

So, two questions:

  1. Is it "bad practice" to store data in the state (as I only plan to read it and not modify it)
  2. Any idea what am I doing wrong in approach 2?

Upvotes: 0

Views: 1941

Answers (1)

Quentin
Quentin

Reputation: 944443

Is it "bad practice" to store data in the state

No, this is what the state is for.

(as I only plan to read it and not modify it)

You are modifying it: You are changing it from the default value to the value from the HTTP request.

Any idea what am I doing wrong in approach 2?

That is a FAQ

Upvotes: 2

Related Questions