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:
- Is it "bad practice" to store data in the state (as I only plan to read it and not modify it)
- Any idea what am I doing wrong in approach 2?