I am using React hooks and trying to figure out, how should I store the response of the api call response.data._embedded.assets in a state variable.
Using setAssets(response.data._embedded.assets); doesn't work because of re-rendering. So I decided to use useEffect as shown in the code below but this violates the rules of react
hooks -Hooks can only be called inside of the body of a function component. I understand that useEffect should be defined outside as per react hooks but then how would I store the response in a state variable ? Please advise.
const [selectedTabIndex, setselectedTabIndex] = useState(0);
const [assets,setAssets] = useState([]);
let companyCategory;
axios
.get(url, {
params: {
assetCategoryId: selectedTabIndex
}
}).then(response => {
if (sessionStorage.getItem('companyCategory') !== null) {
companyCategory = JSON.parse(sessionStorage.getItem('companyCategory') )
}
console.log("Inside response of web api call");
console.log(response.data._embedded.assets);
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setAssets(response.data._embedded.assets);
}, []);
//setAssets(response.data._embedded.assets);
}).catch(err => console.log(err));
In a class component, the above state variable declaration would be like this inside the response:
this.setState({
companyCategory: companyCategory,
assets: response.data._embedded.assets
})
Using setAssets(response.data._embedded.assets); doesn't work because of re-renderingbut that doesn't make sense. Shouldn't you WANT to re-render, after receiving a response, because that's when you have actual data to display?useEffect(() => {}, [])(auseEffectwithout any dependencies listed in the[]is equivalent tocomponentDidMount) and callsetAssetsfrom that. The reason you get the too many re-renders is because your API call is re-done every re-render, which then updates state, which re-renders component, which triggers the api call, etcsetAssets(response.data._embedded.assets);there was some sort of loop I can see in console log which was never ending. What might be causing this?Kevin C. Ferronmentioned as his answer below?