0

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?
zenzone
  • 85
  • 6
  • 1
    There is no problem I think. I use it inside my own library [react-axios-api](https://www.npmjs.com/package/react-axios-api), and it's used too in `redux-toolkit`.... – BENARD Patrick Sep 16 '21 at 12:57
  • 1
    please check this link for Question 2 https://stackoverflow.com/questions/56155959/what-does-it-mean-to-move-this-variable-directly-inside-useeffect-in-this-erro I am getting this error : Assignments to the 'data' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect. (react-hooks/exhaustive-deps)eslint – Vivek Chauhan Sep 16 '21 at 13:36
  • I think approach 2 is anti pattern. Approach 1 right.. this is what the state is for – LiH Sep 16 '21 at 14:30

1 Answers1

2

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335